Authentication overview
Bybit's application programming interface (API) provides programmatic access to its cryptocurrency trading platform, allowing developers to manage accounts, execute trades, and retrieve market data. Authentication for the Bybit API primarily relies on an API key and secret pair, combined with a cryptographic signing mechanism. This approach ensures that only authorized requests from legitimate users can interact with their accounts.
Each request sent to the Bybit API, particularly for private endpoints that access user-specific data or execute actions, must include specific authentication headers and parameters. These typically involve the API key, a timestamp, and a signature generated using the secret key and the request's payload. This method is a common practice in secure API design, providing both authentication (proving the user's identity) and integrity (ensuring the request hasn't been tampered with).
The Bybit API supports various market types, including Inverse, USDT Perpetuals, Spot, and USDC Perpetuals & Futures, each with its own set of endpoints requiring proper authentication. Developers should refer to the specific documentation for each API type, as parameter requirements and signature generation nuances may vary slightly across these different interfaces, as detailed in the official Bybit API documentation.
Supported authentication methods
Bybit employs a signature-based authentication scheme for its API. This method involves using a combination of an API key and a secret key to generate a unique digital signature for each request. The server then verifies this signature to confirm the request's authenticity and integrity.
- API Key: A public identifier associated with your account, used to identify the sender of the request.
- Secret Key: A private, confidential key known only to you and Bybit. It is used to create the signature and must be kept secure.
- HMAC SHA256 Signature: A hash-based message authentication code generated using the secret key, a timestamp, and the request parameters. This signature proves that the request originated from the legitimate owner of the API key and that its contents have not been altered in transit. This standard is widely recognized for its cryptographic strength in API security, as described by the IETF in RFC 2104.
The choice of HMAC SHA256 as the signing algorithm aligns with industry best practices for securing API communications, providing a robust mechanism against tampering and unauthorized access.
Authentication method comparison
| Method | When to Use | Security Level |
|---|---|---|
| API Key & Secret (HMAC SHA256) | All private API requests (trading, account management, withdrawals) | High (requires secure handling of secret key) |
| No Authentication | Public API requests (market data, order book, ticker information) | N/A (public data, no user-specific access) |
Getting your credentials
To interact with the Bybit API programmatically, you first need to generate an API key and secret key pair from your Bybit account. This process is typically performed through the Bybit website's user interface. The steps generally involve:
- Login to your Bybit account: Access your account on the official Bybit website.
- Navigate to API Management: Look for a section like 'API Management' or 'API Keys' within your account settings or profile. The exact path may vary but is usually found under security or account settings.
- Create New Key: Select the option to create a new API key. You will typically be prompted to set various permissions for this key.
- Configure Key Permissions:
- Read-only: Allows retrieval of account information and market data.
- Trade: Enables placing and canceling orders.
- Withdrawal: Grants permission for fund withdrawals (highest level of access, requiring extreme caution).
- Set IP Whitelisting (Optional but Recommended): You can restrict API key usage to specific IP addresses. This enhances security by ensuring that API requests can only originate from trusted network locations. This is a critical security measure for production environments, as noted in general API best practices provided by sources like Twilio's API security guide.
- Note API Key and Secret: Once generated, the API Key and Secret Key will be displayed. The secret key is typically shown only once upon creation. It is crucial to record both keys securely, as Bybit cannot recover a lost secret key. Treat your secret key with the same confidentiality as your account password.
- Enable Two-Factor Authentication (2FA): Ensure that 2FA is enabled on your Bybit account before generating API keys. This adds an extra layer of security to prevent unauthorized key creation or modification.
For detailed, up-to-date instructions, always refer to the specific Bybit API documentation for key creation.
Authenticated request example
An authenticated request to the Bybit API typically involves constructing a URL, preparing a query string or request body, and then generating an HMAC SHA256 signature using your API secret. This signature, along with your API key and a timestamp, is included in the request headers or parameters.
Here's a conceptual example of how to make an authenticated request, focusing on the signature generation process. This example uses Python, which is one of the languages for which Bybit provides SDKs, simplifying this process significantly.
import hmac
import hashlib
import time
import requests
import json
# --- Your Bybit API Credentials ---
API_KEY = "YOUR_API_KEY"
API_SECRET = "YOUR_API_SECRET"
# --- Request Parameters ---
# For GET requests, parameters go into the query string.
# For POST requests, parameters go into the request body (JSON format).
# Example: Get wallet balance
endpoint = "/v5/account/wallet-balance"
category = "spot" # Example category for v5 API
# Prepare request parameters (example for a GET request)
# These need to be sorted alphabetically by key for signature generation
parameters = {
"category": category,
"accountType": "UNIFIED", # Example parameter
"timestamp": int(time.time() * 1000) # Current timestamp in milliseconds
}
# Convert parameters to a query string for signature generation
# For GET requests, parameters are part of the URL query string
# For POST requests, the entire JSON body (as a string) is used.
# The Bybit documentation specifies the exact string to be signed.
# For v5 API, a common signing string format is: timestamp + API_KEY + recv_window + query_string
# where recv_window is an optional parameter defining the time in ms for which the request is valid.
# Let's assume the signature string is 'timestamp + API_KEY + recv_window + query_string' as per docs.
recv_window = 5000 # 5 seconds
timestamp_ms = parameters["timestamp"]
# Sort parameters alphabetically by key
sorted_params = sorted(parameters.items())
query_string = "&".join([f"{k}={v}" for k, v in sorted_params])
# Construct the string to be signed
# NOTE: Refer to the official Bybit API documentation for the *exact* signing string format for your chosen API version (v3, v5) and request type (GET/POST).
# This example assumes a common pattern for v5 GET requests.
param_str_for_signature = f"{timestamp_ms}{API_KEY}{recv_window}{query_string}"
# Generate the signature
signature = hmac.new(bytes(API_SECRET, "utf-8"),
bytes(param_str_for_signature, "utf-8"),
hashlib.sha256).hexdigest()
# --- Construct the full request URL and headers ---
base_url = "https://api.bybit.com"
full_url = f"{base_url}{endpoint}?{query_string}"
headers = {
"X-BAPI-API-KEY": API_KEY,
"X-BAPI-TIMESTAMP": str(timestamp_ms),
"X-BAPI-SIGN": signature,
"X-BAPI-RECV-WINDOW": str(recv_window) # Include recv_window in header as well
}
# Make the request
try:
response = requests.get(full_url, headers=headers)
response.raise_for_status() # Raise an exception for HTTP errors
print("-------- Request URL --------")
print(full_url)
print("-------- Request Headers --------")
print(json.dumps(headers, indent=2))
print("-------- Response --------")
print(json.dumps(response.json(), indent=2))
except requests.exceptions.RequestException as e:
print(f"Error during API request: {e}")
if response is not None:
print(f"Response content: {response.text}")
Important Considerations:
- API Version: Bybit has multiple API versions (e.g., V3, V5). The exact signing methodology and required parameters can differ. Always consult the official Bybit API documentation for the specific version you are using.
recv_window: This parameter specifies the time in milliseconds that the request is valid. If the request is not processed by the server within this window, it will be rejected. This helps prevent replay attacks.- Timestamp Synchronization: Ensure your system's clock is synchronized with a reliable NTP server to avoid timestamp-related authentication failures.
- POST Requests: For POST requests, the request body (typically JSON) is usually included in the string to be signed. The specific format (e.g., JSON string vs. URL-encoded form data) is critical and must match the Bybit specification.
- SDKs: Bybit provides official and community-contributed SDKs (Python, Java, Node.js, Go) that abstract away much of the signature generation complexity, making integration easier. Using an SDK is generally recommended to avoid common implementation errors.
Security best practices
Securing your Bybit API keys and API interactions is paramount to protecting your assets and preventing unauthorized trading. Adhering to these best practices can significantly reduce security risks:
- Principle of Least Privilege: When creating API keys, grant only the minimum necessary permissions. For example, if your application only needs to read market data, do not grant trading or withdrawal permissions. Regularly review and adjust permissions as your requirements change.
- IP Whitelisting: Always configure IP whitelisting for your API keys. This restricts API access to only a predefined list of trusted IP addresses. If your application's IP address changes, remember to update the whitelist on Bybit.
- Secure Storage of Secret Keys: Never hardcode API secret keys directly into your source code. Store them in environment variables, secure configuration files, or a dedicated secret management service (e.g., AWS Secrets Manager, Google Secret Manager, HashiCorp Vault). Access to these storage locations should be tightly controlled.
- Rotate API Keys Regularly: Periodically generate new API keys and revoke old ones. This practice limits the window of exposure if a key is compromised. The frequency depends on your security policy, but quarterly or bi-annually is a good starting point.
- Implement Time Synchronization: Ensure the server making API requests has its clock synchronized with Network Time Protocol (NTP) servers. Significant clock drift can lead to signature validation failures due to timestamp discrepancies.
- Handle Nonces/Timestamps Correctly: The timestamp in your requests should be monotonically increasing or unique per request within a short window to prevent replay attacks. Bybit's API utilizes a timestamp in milliseconds.
- Error Handling and Monitoring: Implement robust error handling in your API integration to detect and log authentication failures. Monitor these logs for unusual patterns that might indicate attempted unauthorized access.
- Use Official SDKs: Whenever possible, use the official Bybit SDKs (Python, Java, Node.js, Go). These libraries are maintained by Bybit or the community and are designed to handle the complexities of signature generation and request construction correctly and securely.
- Enable Two-Factor Authentication (2FA): Ensure 2FA is enabled on your Bybit account itself. This protects against unauthorized access to your account where API keys are managed.
- Avoid Public Repositories: Never commit API keys or secrets to public version control repositories (e.g., GitHub). Use
.gitignorefiles to exclude sensitive configuration files.
By implementing these measures, developers can significantly enhance the security posture of their applications interacting with the Bybit API, protecting both their own and their users' assets.