# Node.js Example for Calling 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).
* Ensure that your Node.js environment has the `axios` library installed. You can install it using:

```bash
npm install axios
```

***

#### Example Code

```js
const axios = require('axios');
const crypto = require('crypto');

const API_KEY = 'your_api_key'; // Replace with your actual API Key
const API_SECRET = 'your_api_secret'; // Replace with your actual API Secret
const BASE_URL = 'https://api.catfee.io';

// Generate the current timestamp in ISO 8601 format
function generateTimestamp() {
    return new Date().toISOString();
}

// Build request path including query parameters
function buildRequestPath(path, queryParams) {
    if (!queryParams || Object.keys(queryParams).length === 0) {
        return path;
    }
    const queryString = new URLSearchParams(queryParams).toString();
    return `${path}?${queryString}`;
}

// Generate signature using HMAC-SHA256
function generateSignature(timestamp, method, requestPath) {
    const signString = timestamp + method + requestPath;
    return crypto.createHmac('sha256', API_SECRET)
                 .update(signString)
                 .digest('base64');
}

// Create and send HTTP request
async function createRequest(url, method, timestamp, signature) {
    const headers = {
        'Content-Type': 'application/json',
        'CF-ACCESS-KEY': API_KEY,
        'CF-ACCESS-SIGN': signature,
        'CF-ACCESS-TIMESTAMP': timestamp
    };

    try {
        const response = await axios({
            url,
            method,
            headers,
        });
        return response.data;
    } catch (error) {
        console.error('Error: ', error.response ? error.response.data : error.message);
        throw error;
    }
}

async function main() {
    const method = 'POST'; // Can be changed to "GET", "PUT", "DELETE"
    const path = '/v1/order';

    // Example: Create an order
    const queryParams = {
        quantity: '65000',
        receiver: 'TRON_ADDRESS',
        duration: '1h'
    };

    // Generate timestamp, request path, and signature
    const timestamp = generateTimestamp();
    const requestPath = buildRequestPath(path, queryParams);
    const signature = generateSignature(timestamp, method, requestPath);

    // Compose full request URL
    const url = BASE_URL + requestPath;

    // Send request
    try {
        const response = await createRequest(url, method, timestamp, signature);
        console.log('Response Data: ', response);
    } catch (error) {
        console.error('Request failed', error);
    }
}

// Run the main function
main();
```

***

#### Code Explanation

* **generateTimestamp()**\
  Returns the current UTC timestamp in ISO 8601 format using JavaScript's `toISOString()` method.
* **buildRequestPath()**\
  Constructs the full URL path by appending URL-encoded query parameters. `URLSearchParams` is used to format the query string.
* **generateSignature()**\
  Signs the string composed of `timestamp + method + requestPath` using the HMAC-SHA256 algorithm with your `API_SECRET`, then encodes the result in Base64.
* **createRequest()**\
  Sends the HTTP request using the `axios` library. Sets headers including `CF-ACCESS-KEY`, `CF-ACCESS-SIGN`, and `CF-ACCESS-TIMESTAMP`.
* **main()**\
  Defines the HTTP method and request path, prepares query parameters, generates the necessary headers, and sends the request.

***

#### Notes

* **API Key and Secret**\
  Make sure to replace `API_KEY` and `API_SECRET` with the actual values you obtained from CatFee.IO.
* **Query Parameter Order**\
  This example uses `URLSearchParams` to build the query string without sorting the parameters.
* **Error Handling**\
  Uses `try-catch` to catch and log any potential errors. Server errors can be accessed via `error.response`.
* **Request Method**\
  The example supports `POST`, `GET`, `PUT`, and `DELETE`. You can change the `method` variable accordingly.
* **Response Handling**\
  If the request is successful, `axios` returns `response.data`, which is the response body. You can parse it based on your needs (e.g., JSON).

***

#### Summary

This example demonstrates how to securely call the CatFee.IO REST API in a Node.js environment. It includes HMAC-SHA256 signature generation for request verification and supports multiple HTTP methods. You can modify and expand the code based on your specific API use cases.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.catfee.io/en/getting-started/buy-energy-via-api-on-catfee/nodejs.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
