Getting started overview
This guide outlines the steps for developers to initiate their work with the Coinbase Pro API, focusing on account setup, API key generation, and executing a foundational API request. The Coinbase Pro API provides programmatic access to cryptocurrency spot trading, real-time market data, and account management features. It supports both RESTful endpoints for request/response interactions and WebSockets for streaming data updates. Developers aiming to integrate advanced trading strategies or build custom applications that interact with the Coinbase Pro exchange will follow these initial procedures.
The process involves several key stages:
- Account Creation and Verification: Establishing a Coinbase Pro account and completing necessary identity verification.
- API Key Generation: Creating and securely storing API credentials (key, secret, and passphrase).
- Environment Setup: Configuring a development environment to make API calls.
- First API Request: Executing a simple, authenticated API call to confirm connectivity and credentials.
Adhering to these steps ensures a secure and functional setup for subsequent development efforts. For a comprehensive overview of the API's capabilities, developers can consult the Coinbase Exchange API documentation.
Create an account and get keys
To access the Coinbase Pro API, you must first create a Coinbase Pro account and complete the required identity verification. This process ensures compliance with regulatory standards, including the NYDFS BitLicense.
Follow these steps to set up your account and generate API keys:
- Register for a Coinbase Pro Account: Navigate to the Coinbase Pro homepage and sign up. If you already have a Coinbase.com account, you can typically use the same credentials to log into Coinbase Pro.
- Complete Identity Verification (KYC): Coinbase Pro requires users to complete Know Your Customer (KYC) verification. This typically involves providing personal information, uploading identification documents, and potentially linking a bank account. The verification level dictates transaction limits and API access permissions.
- Navigate to API Settings: Once logged in and verified, go to your account settings. Look for a section labeled 'API' or 'API Settings'. The exact location may vary slightly with UI updates, but it is generally found under your profile or security settings.
- Create New API Key: Within the API settings, select the option to 'New API Key' or 'Generate API Key'. You will be prompted to:
- Name the API Key: Assign a descriptive name to help you identify its purpose (e.g., 'MyTradingBot' or 'MarketDataApp').
- Set Permissions: Carefully select the permissions required for your application. For a read-only request, 'view' permissions are sufficient. For trading, you will need 'trade' permissions. Avoid granting more permissions than necessary to minimize security risks.
- Specify IP Whitelist (Optional but Recommended): For enhanced security, you can restrict API key usage to specific IP addresses. If your application will run from a fixed server, whitelist its IP. For dynamic IPs, this step might be skipped initially but is recommended for production environments.
- Record API Key, API Secret, and Passphrase: After creating the key, Coinbase Pro will display three critical pieces of information:
- API Key: A unique identifier for your application.
- API Secret: A cryptographic key used to sign your requests. This is shown only once; store it securely.
- Passphrase: An additional secret required for authentication, also displayed once.
Important: Store your API Secret and Passphrase securely. Do not embed them directly in client-side code, commit them to public repositories, or share them. Consider using environment variables or a secure vault for production applications. If you lose your API Secret or Passphrase, you will need to revoke the existing key and generate a new one.
Your first request
After obtaining your API Key, API Secret, and Passphrase, you can make your first authenticated request. This example demonstrates fetching your account balances using the REST API. We will use curl for simplicity, but the principles apply to any programming language or HTTP client.
All authenticated Coinbase Pro API requests require specific HTTP headers for authentication. These include:
CB-ACCESS-KEY: Your API Key.CB-ACCESS-SIGN: The cryptographic signature of your request.CB-ACCESS-TIMESTAMP: The current timestamp in Unix epoch format.CB-ACCESS-PASSPHRASE: Your API Passphrase.
The CB-ACCESS-SIGN header is generated by creating a SHA256 HMAC of the prehash string, using your API Secret as the key. The prehash string is constructed as: timestamp + method + requestPath + body.
timestamp: Unix epoch, seconds.method: HTTP method (e.g.,GET,POST).requestPath: The path portion of the URL (e.g.,/accounts).body: The request body if present, or an empty string forGETrequests.
Here's a simplified Python example to generate the signature and make a request to the /accounts endpoint:
import hmac
import hashlib
import time
import requests
import json
# Replace with your actual API credentials
API_KEY = "YOUR_API_KEY"
API_SECRET = "YOUR_API_SECRET"
API_PASSPHRASE = "YOUR_API_PASSPHRASE"
BASE_URL = "https://api.exchange.coinbase.com"
def sign_request(method, request_path, body=""):
timestamp = str(int(time.time()))
message = timestamp + method + request_path + body
hmac_key = API_SECRET.encode('utf-8')
signature = hmac.new(hmac_key, message.encode('utf-8'), hashlib.sha256).hexdigest()
return timestamp, signature
def get_accounts():
method = "GET"
request_path = "/accounts"
timestamp, signature = sign_request(method, request_path)
headers = {
"CB-ACCESS-KEY": API_KEY,
"CB-ACCESS-SIGN": signature,
"CB-ACCESS-TIMESTAMP": timestamp,
"CB-ACCESS-PASSPHRASE": API_PASSPHRASE,
"Content-Type": "application/json"
}
try:
response = requests.get(BASE_URL + request_path, headers=headers)
response.raise_for_status() # Raise an exception for HTTP errors (4xx or 5xx)
return response.json()
except requests.exceptions.HTTPError as err:
print(f"HTTP error occurred: {err}")
if response.status_code == 401:
print("Check your API Key, Secret, and Passphrase, or IP whitelist settings.")
print(f"Response body: {response.text}")
return None
except requests.exceptions.RequestException as err:
print(f"Request error occurred: {err}")
return None
if __name__ == "__main__":
accounts = get_accounts()
if accounts:
print(json.dumps(accounts, indent=2))
To execute this:
- Save the code as a
.pyfile (e.g.,coinbase_pro_test.py). - Replace
"YOUR_API_KEY","YOUR_API_SECRET", and"YOUR_API_PASSPHRASE"with your actual credentials. - Run the script from your terminal:
python coinbase_pro_test.py.
A successful response will return a JSON array of your Coinbase Pro accounts and their balances. If an error occurs, the script will print an error message, which can help in troubleshooting.
Common next steps
After successfully making your first authenticated call, consider these next steps to further your integration with Coinbase Pro:
- Explore Public Endpoints: Access market data without authentication, such as product lists (
/products) or historic rates (/products/<product-id>/candles). This can be useful for displaying real-time prices or building charting tools. - Implement Trading Functionality: If your application requires placing or canceling orders, explore the
/ordersendpoint. Ensure your API key has the necessary 'trade' permissions. - Utilize WebSockets for Real-time Data: For applications requiring immediate updates on market changes or user activities, integrate the Coinbase Exchange WebSocket Feed. This allows for streaming data rather than polling REST endpoints.
- Error Handling and Rate Limits: Implement robust error handling for various API responses. Familiarize yourself with Coinbase Pro's rate limits to prevent your application from being temporarily blocked.
- Secure Credential Management: For production deployments, move API keys and secrets out of source code. Use environment variables, a secrets management service (e.g., AWS Secrets Manager, Google Secret Manager), or a configuration management system.
- Explore SDKs (if available): While the entity payload indicates no official SDKs, community-contributed libraries might exist. Evaluate their security and maintenance status before integration.
Troubleshooting the first call
Encountering issues during your initial API call is common. Here's a quick reference table for diagnosing and resolving common problems:
| Problem | What to Do | Where to Check |
|---|---|---|
401 Unauthorized |
Incorrect API Key, Secret, Passphrase, or signature. |
|
403 Forbidden |
Insufficient API key permissions or IP whitelist restriction. |
|
400 Bad Request |
Malformed request, invalid parameters, or incorrect headers. |
|
429 Too Many Requests |
Exceeded API rate limits. |
|
| Connection Timeout | Network issues or incorrect base URL. |
|
By systematically checking these points, you can often identify and resolve issues quickly. Always refer to the official Coinbase Exchange API documentation for the most up-to-date information on endpoints, parameters, and error codes.