# Python Example for Calling API

### Prerequisites

[You need a valid **API Key** and **API Secret**](https://docs.catfee.io/en/getting-started/api-overview#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.6 or above**.

***

### Example Code

```python
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

* **`generate_timestamp()`**\
  Generates the current UTC timestamp in ISO 8601 format using `time.strftime('%Y-%m-%dT%H:%M:%S.000Z')`.
* **`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()`**\
  The main function sets the HTTP method, prepares query parameters, builds headers and request path, sends the request, and prints the response.

***

### Notes

* **API Key and Secret**\
  Replace `API_KEY` and `API_SECRET` with the actual credentials you obtained from CatFee.IO.
* **Error Handling**\
  If the response status code is not 200, the code will print the error details.
* **HTTP Methods**\
  This example supports POST, GET, PUT, and DELETE. You can modify the `method` variable based on your needs.

***

### 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.
