# Getting Started with Mefree.NET REST API

#### **Getting Started with Mefree.NET REST API**

This guide will help you quickly get started with connecting to and using Mefree.NET's REST API for TRON energy services.

***

#### **1. Preparation**

**1.1 Register and Obtain API Keys**

1. Log in to Mefree.NET's Telegram bot ([**@SuperXCoinBot**](https://t.me/SuperXCoinBot)).
2. Navigate to the **Personal Center** section and click on **API Purchase**.
3. Save the following:
   * **API Key (MF-ACCESS-KEY)**
   * **API Secret (MF-ACCESS-SECRET)**

**1.2 Tools and Environment**

* **Testing Tools**: Use tools like **Postman**, **Curl**, or command-line utilities.
* **Development Environment**: Python (recommended with the `requests` library), or any programming language that supports HTTP requests.

**1.3 Reference Documentation**

Visit the [**Mefree.NET Official API Documentation**](/api/config.md) for detailed descriptions of available endpoints and parameters.

***

#### **2. API Basics**

**2.1 Base URL**

* **Production Environment**: `https://api.mefree.net`

**2.2 API Headers**

Every request must include the following HTTP headers:

* `Content-Type`: `application/json`
* `MF-ACCESS-KEY`: Your API key
* `MF-ACCESS-SIGN`: Request signature (see signature rules below)
* `MF-ACCESS-TIMESTAMP`: Current timestamp

**2.3 Timestamp Format**

The `MF-ACCESS-TIMESTAMP` must be in **ISO 8601** format using UTC, e.g., `2023-01-01T12:00:00.000Z`.

**2.4 Signature Rules**

The signature ensures secure communication. Follow these steps to generate the signature:

1. Concatenate the following string to be signed:

   ```
   sign = timestamp + method + requestPath
   ```

   * `timestamp`: Value of `MF-ACCESS-TIMESTAMP`.
   * `method`: HTTP method (e.g., `GET`, `POST`).
   * `requestPath`: Path of the API endpoint,:warning: NOTICE: If there are query parameters, they must be appened at the end (e.g., `/api/config`,`/api/order?quantity=65000&period=1&target_address=Txx...xx`).
2. Use the **HMAC-SHA256** algorithm with your **API Secret Key** to hash the string.
3. Encode the hashed result using Base64 to obtain the signature.

***

#### **3. Quick Request Examples**

**3.1 Set Up Your Development Environment**

Install the required Python libraries:

```bash
pip install requests
```

**3.2 Example: Query Account Balance**

**Request Details**

* **URL**: `GET /api/config`
* **Function**: Fetch account information.

**Code Implementation**

```python
import requests
import time
import base64
import hmac
from datetime import datetime

# API Configuration
BASE_URL = "https://api.mefree.net"
API_KEY = "your_api_key"
SECRET_KEY = "your_secret_key"

# Generate Signature
def generate_signature(timestamp, method, request_path, secret_key):
    message = f"{timestamp}{method}{request_path}"
    mac = hmac.new(secret_key.encode('utf-8'), message.encode('utf-8'), digestmod='sha256')
    return base64.b64encode(mac.digest()).decode()

# Set Request Details
timestamp = datetime.utcnow().isoformat(timespec='milliseconds') + 'Z'
method = "GET"
request_path = "/api/config"

# Generate Signature
signature = generate_signature(timestamp, method, request_path, SECRET_KEY)

# Set Headers
headers = {
    "Content-Type": "application/json",
    "MF-ACCESS-KEY": API_KEY,
    "MF-ACCESS-SIGN": signature,
    "MF-ACCESS-TIMESTAMP": timestamp,
}

# Send Request
response = requests.get(BASE_URL + request_path, headers=headers)
if response.status_code == 200:
    print("Account Information:", response.json())
else:
    print("Request Failed:", response.status_code, response.text)
```

***

**3.3 Example: Place an Order for Energy**

**Request Details**

* **URL**: `POST /api/order`
* **Function**: Purchase energy.

**Code Implementation**

```python
# Generate Timestamp and Signature
timestamp = datetime.utcnow().isoformat(timespec='milliseconds') + 'Z'
method = "POST"
request_path = "/api/order?quantity=65000&receiver=TDYk....4rnPfkdPZ&period=1"

# Generate Signature
signature = generate_signature(timestamp, method, request_path, SECRET_KEY)

# Set Headers
headers = {
    "Content-Type": "application/json",
    "MF-ACCESS-KEY": API_KEY,
    "MF-ACCESS-SIGN": signature,
    "MF-ACCESS-TIMESTAMP": timestamp,
}

# Send Request
response = requests.post(BASE_URL + request_path, headers=headers, json=body)
if response.status_code == 200:
    print("Order Created:", response.json())
else:
    print("Request Failed:", response.status_code, response.text)
```

***

#### **4. Common Issues and Solutions**

1. **HTTP Status Code 401 (Unauthorized):**
   * Verify the `MF-ACCESS-KEY` and `MF-ACCESS-SIGN` values.
   * Ensure your API key has the required permissions enabled.
2. **HTTP Status Code 400 (Bad Request):**
   * Check if your request parameters (e.g., quantity, receiver) are correct.
3. **Signature Errors:**
   * Make sure the timestamp uses UTC format and the signature follows the required rules.

***

#### **5. Next Steps**

* Explore the [**Mefree.NET API Documentation**](/api/config.md) for more advanced features (e.g., retrieving order details, available energy).
* Integrate the API into your system to automate energy purchases and optimize resource usage.
* Build custom tools or platforms to manage energy trading more efficiently.
* **If you have any question, please contact us** [**@mefreenet**](https://t.me/mefreenet)**.**

By following this guide, you’ve completed the basics of connecting to the Mefree API. Best of luck with your TRON energy operations!


---

# 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.mefree.net/getting-started/how-to-buy-energy/buy-energy-by-api-quickstart.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.
