Getting started overview
This guide provides a structured approach to initiating development and integration with Localbitcoins. It focuses on the fundamental steps required to go from account creation to executing a basic, authenticated request. Localbitcoins operates primarily as a user-facing peer-to-peer (P2P) platform for buying and selling Bitcoin, emphasizing direct interactions between users. The programmatic access offered is designed to support specific functionalities, such as managing trade advertisements rather than broad exchange operations.
The process involves registering a user account, undergoing identity verification (KYC/AML) as required by regulatory standards, and then obtaining API credentials. These credentials are vital for authenticating any programmatic interactions with the Localbitcoins platform. Understanding the platform's P2P model is crucial, as the API reflects this architecture, primarily enabling the creation and management of trade offers.
Before proceeding, ensure you have a clear understanding of how Localbitcoins functions as a P2P marketplace. This context will help in effectively utilizing the API to automate or enhance your trading activities, such as setting up new advertisements for buying or selling Bitcoin, or tracking the status of existing ones.
Here’s a quick reference table outlining the essential steps:
| Step | What to Do | Where |
|---|---|---|
| 1. Account Creation | Register a new user account. | Localbitcoins registration page |
| 2. Verification | Complete identity verification (KYC/AML). | Localbitcoins profile settings > Verification |
| 3. API Key Generation | Generate API Key and API Secret. | Localbitcoins profile settings > API Access |
| 4. First Request | Construct and send an authenticated API call. | Using a cURL command or programming language HTTP client |
Create an account and get keys
Accessing the Localbitcoins API requires an active user account with appropriate verification levels. Follow these steps to set up your account and retrieve the necessary API credentials:
-
Register a Localbitcoins Account: Navigate to the official Localbitcoins registration page. Provide a unique username, email address, and a strong password. You will need to verify your email address to activate your account.
-
Complete Identity Verification (KYC/AML): Localbitcoins, like many financial platforms, adheres to Know Your Customer (KYC) and Anti-Money Laundering (AML) regulations. This typically involves submitting identification documents and proof of address. The specific requirements may vary based on your region and the level of trading activity you intend. You can usually find the verification section within your profile settings. Completing this step is often mandatory before gaining full access to trading features and, critically, API key generation. Consult the Localbitcoins support documentation for detailed verification procedures.
-
Enable Two-Factor Authentication (2FA): While not strictly required for API key generation, enabling 2FA for your account is a critical security measure recommended by security best practices for online accounts. This adds an extra layer of protection to your account access and API keys.
-
Generate API Keys: Once your account is active and verified, log in to Localbitcoins. Navigate to your profile settings, typically found under your username in the top right corner. Look for a section labeled API Access or API Keys. Here, you will find options to generate a new API Key and API Secret. The API Key is a public identifier for your application, while the API Secret is a confidential key used to sign your requests. Treat your API Secret with the same level of security as your account password.
- API Key: A string that identifies your application.
- API Secret: A secret string used to create a digital signature for authenticating your requests. It should never be exposed publicly.
-
Store Keys Securely: After generation, copy both the API Key and API Secret immediately. Localbitcoins typically displays the secret only once. Store these credentials in a secure location, such as an environment variable, a secrets manager, or a secure configuration file, keeping them out of your public code repositories.
Your first request
Localbitcoins utilizes OAuth 1.0a for API authentication. This means each request must be signed with your API Key and API Secret. We'll demonstrate a simple request using cURL to fetch information about your account balance. This endpoint, /api/wallet-balance/, is a good starting point as it does not modify any data.
Authentication Process (OAuth 1.0a)
To make an authenticated request, you need to generate an OAuth 1.0a signature. This involves several parameters:
oauth_consumer_key: Your API Key.oauth_nonce: A unique, random string for each request.oauth_signature_method: AlwaysHMAC-SHA256for Localbitcoins.oauth_timestamp: The current Unix timestamp (seconds since epoch).oauth_version: Always1.0.oauth_token: (Optional) Not needed for initial calls if you don't have a user access token yet, but it's part of the OAuth 1.0a specification. For basic API key authentication, it's often omitted or set to an empty string.
These parameters, along with the HTTP method (GET, POST), the request URL, and any query/body parameters, are used to construct a signature base string. This string is then signed using HMAC-SHA256 with your API Secret as the key. The resulting signature is then included in the Authorization header.
Example: Fetching Wallet Balance with Python
While cURL can be used, creating the OAuth 1.0a signature manually is complex. Using a library is highly recommended. Here's a Python example using the requests_oauthlib library:
import os
import requests
from requests_oauthlib import OAuth1Session
# Retrieve API Key and Secret from environment variables for security
API_KEY = os.environ.get('LOCALBITCOINS_API_KEY')
API_SECRET = os.environ.get('LOCALBITCOINS_API_SECRET')
if not API_KEY or not API_SECRET:
print("Error: LOCALBITCOINS_API_KEY and LOCALBITCOINS_API_SECRET environment variables must be set.")
exit(1)
# Base URL for Localbitcoins API
BASE_URL = "https://localbitcoins.com"
# Endpoint to fetch wallet balance
ENDPOINT = "/api/wallet-balance/"
# Create an OAuth1Session object
# The client_secret is your API_SECRET, used for signing requests
localbitcoins = OAuth1Session(API_KEY, client_secret=API_SECRET)
# Make the request
try:
response = localbitcoins.get(BASE_URL + ENDPOINT)
response.raise_for_status() # Raise an exception for HTTP errors
# Print the JSON response
print("Wallet Balance:")
print(response.json())
except requests.exceptions.HTTPError as err:
print(f"HTTP error occurred: {err}")
print(f"Response content: {response.text}")
except requests.exceptions.RequestException as err:
print(f"Other request error occurred: {err}")
To run this example:
- Install
requests_oauthlib:pip install requests-oauthlib - Set environment variables:
Replaceexport LOCALBITCOINS_API_KEY="YOUR_API_KEY" export LOCALBITCOINS_API_SECRET="YOUR_API_SECRET"YOUR_API_KEYandYOUR_API_SECRETwith your actual credentials. - Save and Run: Save the Python code as
localbitcoins_balance.pyand execute it:python localbitcoins_balance.py
A successful response will return a JSON object containing your wallet balance and other related information, similar to:
{
"data": {
"total": {
"sendable": "0.00000000",
"receiving": "0.00000000",
"total": "0.00000000"
},
"currency": "BTC"
},
"error": {
"name": "",
"message": ""
}
}
Your specific balance will vary. If your account is new or has no funds, the values will be zero.
Common next steps
After successfully making your first authenticated call, consider these next steps to further your integration with Localbitcoins:
-
Explore Other Endpoints: Consult the Localbitcoins API documentation to understand available endpoints. Common next steps include:
/api/ads/: To list your advertisements./api/ad-create/: To create new buy or sell advertisements./api/contact_info/: To retrieve specific trade contact information./api/dashboard/: To get an overview of your active trades.
-
Implement Webhooks: For real-time notifications about trades, messages, or payments, explore setting up webhooks. This allows Localbitcoins to push updates to your application, reducing the need for constant polling. Webhooks typically require you to provide a publicly accessible URL where Localbitcoins can send POST requests with event data. Ensure your webhook endpoint is secure and can validate incoming requests.
-
Error Handling and Logging: Implement robust error handling in your application. This includes catching HTTP errors (e.g., 4xx client errors, 5xx server errors) and parsing error messages from the API response. Logging requests and responses is crucial for debugging and monitoring your integration.
-
Rate Limiting: Be aware of and respect Localbitcoins's API rate limits. Exceeding these limits can lead to temporary blocks or errors. The documentation typically specifies these limits, often communicated via HTTP response headers. Implement exponential backoff or token bucket algorithms in your application to manage request frequency effectively.
-
Security Best Practices: Continuously review and apply security best practices. Beyond securing your API keys, consider input validation, output encoding, and protecting against common web vulnerabilities when building applications that interact with financial APIs. For example, be careful when handling sensitive user data and ensure all communication is over HTTPS.
Troubleshooting the first call
Encountering issues during your first API call is common. Here are some troubleshooting tips:
-
Invalid API Key or Secret: Double-check that your
LOCALBITCOINS_API_KEYandLOCALBITCOINS_API_SECRETare copied correctly and match the ones generated in your Localbitcoins account. Even small typos can lead to authentication failures. Remember that the API Secret is only shown once during generation, so ensure it was saved correctly. -
Incorrect OAuth Signature: OAuth 1.0a signature generation is precise. If you're building the signature manually, ensure all parameters (nonce, timestamp, method, URL, query parameters) are correctly ordered and encoded before signing. Using a well-tested OAuth 1.0a library (like
requests_oauthlibin Python) significantly reduces errors here. -
Missing or Incomplete Verification: If your account verification (KYC/AML) is not fully completed or approved, certain API functionalities, including viewing wallet balance, might be restricted. Check your Localbitcoins profile for any pending verification steps.
-
Time Sync Issues: OAuth 1.0a relies on timestamps. If your system's clock is significantly out of sync with the Localbitcoins server, the timestamp in your request might be rejected. Ensure your system's time is synchronized, for example, using NTP (Network Time Protocol).
-
Network Connectivity: Verify that your system has an active internet connection and can reach
https://localbitcoins.com. Proxy settings or firewall rules might interfere with outbound API requests. -
Endpoint or Method Errors: Confirm you are using the correct HTTP method (GET, POST) for the specific endpoint you are calling, and that the endpoint URL is accurate as per the Localbitcoins API documentation. A
404 Not Founderror often indicates an incorrect URL, while a405 Method Not Allowedsuggests the wrong HTTP method. -
Exceeded Rate Limits: If you make too many requests in a short period, you might encounter a
429 Too Many Requestserror. Wait for a few minutes and try again, or implement rate-limiting logic in your code. -
Check Localbitcoins Status: Occasionally, the Localbitcoins API itself might experience downtime or maintenance. Check the Localbitcoins news or status page for any announcements.