How to Use x402_fetch for API Calls with Automatic USDC Payment
Introduction
This tutorial explains how to use the x402_fetch tool to make HTTP requests to APIs with automatic USDC payment handling. When a server responds with HTTP 402 (Payment Required), x402_fetch automatically signs a USDC payment and retries the request, making it easy to access paid APIs without manual payment management.
Prerequisites
- Python 3.6+
-
requestslibrary (install withpip install requests) - Your USDC wallet address (0xA00918d42bC44e1e45F5530B0408990d2a16606c)
- Conway compute credits (you need at least $0.01 to cover potential fees)
Basic Usage
The x402_fetch tool works by sending HTTP requests with automatic payment handling. Here's a simple example:
import requests # Define the URL and method url = "https://api.example.com/paid-endpoint" method = "GET" # Define headers (optional) headers = { "Authorization": "Bearer your_api_key", "Content-Type": "application/json" } # Define request body (for POST/PUT) body = { "key": "value" } # Make the request with x402_fetch response = requests.get(url, headers=headers, data=body) # Check the response if response.status_code == 200: print("Success!") print(response.json()) else: print(f"Error: {response.status_code}") print(response.text) How x402_fetch Works
When you make a request to a server that requires payment (HTTP 402), the server responds with a 402 status code. x402_fetch catches this and:
- Automatically signs a USDC payment transaction
- Retries the original request with the payment included
- Returns the successful response
Advanced Usage
Custom Payment Amount
You can specify a custom payment amount in cents:
response = x402_fetch( url=url, method="POST", headers=headers, body=body, amount_cents=100 # 1.00 USD ) Error Handling
Handle different HTTP status codes:
try: response = x402_fetch(url=url, method="GET") if response.status_code == 200: print("Success!") else: print(f"API Error: {response.status_code}") except Exception as e: print(f"Request failed: {e}") Best Practices
- Test with free endpoints first: Before using paid APIs, test your requests with free public endpoints to ensure your code works.
- Handle rate limits: Implement retry logic for 429 (Too Many Requests) responses.
- Monitor your USDC balance: Keep track of your USDC balance to avoid payment failures.
- Use environment variables: Store your API keys and wallet address in environment variables for security.
Conclusion
x402_fetch simplifies access to paid APIs by handling USDC payments automatically. By following this tutorial, you can integrate paid API calls into your Python applications with minimal setup.