> For the complete documentation index, see [llms.txt](https://docs.catfee.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.catfee.io/en/getting-started/buy-energy-via-api-on-catfee/python.md).

# Python Example for Calling API

Python Example for Calling the CatFee.IO REST API

### Prerequisites

[You need a valid **API Key** and **API Secret**](/en/getting-started/buy-energy-via-api-on-catfee/api-overview.md#apply-api-info).

Make sure your environment has the `requests` library installed. You can install it using:

```bash
pip install requests
```

Use Python version **3.8 or above**.

***

### Example Code

```python
import base64
import hashlib
import hmac
import json
import uuid
from datetime import datetime, timezone
from urllib.parse import urlencode

import requests

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"
TIMEOUT_SECONDS = 15

def generate_timestamp():
    """Generate an ISO 8601 UTC timestamp with milliseconds."""
    return datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace(
        "+00:00", "Z"
    )

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.upper() + 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, timeout=TIMEOUT_SECONDS)
    elif method == "GET":
        response = requests.get(url, headers=headers, timeout=TIMEOUT_SECONDS)
    elif method == "PUT":
        response = requests.put(url, headers=headers, timeout=TIMEOUT_SECONDS)
    elif method == "DELETE":
        response = requests.delete(url, headers=headers, timeout=TIMEOUT_SECONDS)
    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
    client_order_id = str(uuid.uuid4())
    query_params = [
        ("quantity", "65000"),
        ("receiver", "TRON_ADDRESS"),
        ("duration", "1h"),
        ("client_order_id", client_order_id),
        ("activate", "true"),
    ]
    
    # 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
    
    print("Client Order ID:", client_order_id)
    try:
        response = create_request(url, method, timestamp, signature)
        print("HTTP Status:", response.status_code)
        print("Response Body:", response.text)
        response.raise_for_status()

        result = json.loads(response.text)
        if result.get("code") != 0:
            message = result.get("msg") or result.get("sub_msg")
            raise RuntimeError(
                f"API request failed: code={result.get('code')}, message={message}"
            )

        data = result.get("data") or {}
        print("Order ID:", data.get("id"))
    except requests.Timeout:
        print("Request timed out. Retry with the same Client Order ID:", client_order_id)
    except json.JSONDecodeError as error:
        print("Response is not valid JSON:", error)
    except requests.RequestException as error:
        print("HTTP request failed:", error)
    except RuntimeError as error:
        print(error)

if __name__ == "__main__":
    main()
```

***

### Code Explanation

* **`generate_timestamp()`**\
  Generates an ISO 8601 UTC timestamp with milliseconds using `datetime.now(timezone.utc)`.
* **`build_request_path()`**\
  Builds the full request path including query parameters. If no parameters are provided, it returns the original path.
* **`generate_signature()`**\
  Concatenates `timestamp + method + request_path`, then generates a signature using the `hmac_sha256()` function.
* **`hmac_sha256()`**\
  Uses the HMAC-SHA256 algorithm with your `API_SECRET` as the key, and encodes the result with Base64.
* **`create_request()`**\
  Sends the HTTP request using the `requests` library. Supports POST, GET, PUT, and DELETE methods.
* **`main()`**\
  Creates an order, prints its idempotency key, and checks both the HTTP status and the API response `code`.

***

### Notes

* **API Key and Secret**\
  Replace `API_KEY` and `API_SECRET` with the actual credentials you obtained from CatFee.IO.
* **Signed request path**\
  The encoded query string and its parameter order must be identical in the signature and the actual URL.
* **Order parameters**\
  `quantity` must be at least `65000`, `duration` currently supports only `1h`, and `receiver` must be a valid TRON address.
* **Idempotent retries**\
  Use a unique `client_order_id` of no more than 64 characters for each new order. Reuse it after a timeout or connection failure.
* **Response handling**\
  HTTP `200` does not necessarily mean business success. Always verify that the response body's `code` is `0`.

***

### Summary

This example demonstrates how to use Python to securely call the CatFee.IO Rest API. It ensures security through HMAC-SHA256 signature authentication. You can adjust the code as needed to support different endpoints and HTTP methods.

If you have any questions or need further assistance, feel free to contact the CatFee.IO support team.
