Python Example for Calling API
Python Example for Calling the CatFee.IO REST API
Prerequisites
pip install requestsExample Code
import hashlib
import hmac
import base64
import time
import requests
from urllib.parse import urlencode
API_KEY = "your_api_key" # Replace with your actual API Key
API_SECRET = "your_api_secret" # Replace with your actual API Secret
BASE_URL = "https://api.catfee.io"
def generate_timestamp():
"""Generate current timestamp in ISO 8601 format (UTC)"""
return time.strftime('%Y-%m-%dT%H:%M:%S.000Z', time.gmtime())
def build_request_path(path, query_params):
"""Build request path with query parameters"""
if not query_params:
return path
query_string = urlencode(query_params)
return f"{path}?{query_string}"
def generate_signature(timestamp, method, request_path):
"""Generate request signature"""
sign_string = timestamp + method + request_path
return hmac_sha256(sign_string, API_SECRET)
def hmac_sha256(data, secret):
"""Generate HMAC-SHA256 signature"""
return base64.b64encode(
hmac.new(secret.encode('utf-8'), data.encode('utf-8'), hashlib.sha256).digest()
).decode()
def create_request(url, method, timestamp, signature):
"""Create and send HTTP request"""
headers = {
"Content-Type": "application/json",
"CF-ACCESS-KEY": API_KEY,
"CF-ACCESS-SIGN": signature,
"CF-ACCESS-TIMESTAMP": timestamp,
}
if method == "POST":
response = requests.post(url, headers=headers)
elif method == "GET":
response = requests.get(url, headers=headers)
elif method == "PUT":
response = requests.put(url, headers=headers)
elif method == "DELETE":
response = requests.delete(url, headers=headers)
else:
raise ValueError(f"Unsupported HTTP method: {method}")
return response
def main():
method = "POST" # Can be changed to "GET", "PUT", or "DELETE"
path = "/v1/order"
# Example: Create Order
query_params = {
"quantity": "65000",
"receiver": "TRON_ADDRESS",
"duration": "1h"
}
# Generate request headers
timestamp = generate_timestamp()
request_path = build_request_path(path, query_params)
signature = generate_signature(timestamp, method, request_path)
# Construct full request URL
url = BASE_URL + request_path
# Send request
response = create_request(url, method, timestamp, signature)
# Print response
print("Response Code:", response.status_code)
print("Response Body:", response.text)
# Handle possible error
if response.status_code != 200:
print("Error:", response.json())
if __name__ == "__main__":
main()Code Explanation
Notes
Summary
Last updated