> For the complete documentation index, see [llms.txt](https://docs.apismart.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.apismart.ai/sdks-and-migration/python.md).

# Python

Use Python to send requests to the ApiSmart API with the `requests` library.

This guide shows a basic setup for Chat Completions, image generation, and video generation.

For general API rules, see [**API Basics**](/api-guides/api-basics.md).

***

### Before You Begin

Make sure you have:

* Python 3 installed
* An active **API Token**
* Sufficient **Current Balance**
* A valid **Model ID**

Install `requests`:

```bash
pip install requests
```

Set your API Token as an environment variable:

```bash
export APISMART_API_KEY="YOUR_API_KEY"
```

On PowerShell:

```powershell
$env:APISMART_API_KEY="YOUR_API_KEY"
```

***

### Basic Setup

```python
import os
import requests

api_key = os.getenv("APISMART_API_KEY")

if not api_key:
    raise RuntimeError("APISMART_API_KEY is not set.")

headers = {
    "Authorization": f"Bearer {api_key}",
    "Content-Type": "application/json",
}
```

Use the same authentication headers for supported ApiSmart endpoints.

***

### Chat Completions

```python
response = requests.post(
    "https://gw.apismart.ai/v1/chat/completions",
    headers=headers,
    json={
        "model": "YOUR_MODEL_ID",
        "messages": [
            {
                "role": "user",
                "content": "Hello!",
            }
        ],
    },
    timeout=120,
)

response.raise_for_status()

result = response.json()
print(result["choices"][0]["message"]["content"])
```

Replace `YOUR_MODEL_ID` with the exact value shown in the selected model’s **Code Example**.

***

### Image Generation

```python
response = requests.post(
    "https://gw.apismart.ai/v1/images/generations",
    headers=headers,
    json={
        "model": "YOUR_MODEL_ID",
        "prompt": "A futuristic city at sunset",
    },
    timeout=120,
)

response.raise_for_status()
result = response.json()

print(result)
```

Image request and response fields may vary by model.

***

### Video Generation

Video generation uses an asynchronous task workflow.

For a video model that accepts `prompt` and `duration`:

```python
response = requests.post(
    "https://gw.apismart.ai/v1/video/tasks",
    headers=headers,
    json={
        "model": "YOUR_MODEL_ID",
        "prompt": "A cinematic view of waves at sunset",
        "duration": 5,
    },
    timeout=120,
)

response.raise_for_status()
result = response.json()

task_id = result["id"]
print(task_id)
```

Check the task status:

```python
response = requests.get(
    f"https://gw.apismart.ai/v1/video/tasks/{task_id}",
    headers=headers,
    timeout=60,
)

response.raise_for_status()
print(response.json())
```

> ⚠️ **Important:** Always use the exact endpoint, Model ID, request fields, and supported values shown in the selected model’s **Code Example**.

***

### Handle API Errors

A simple pattern is:

```python
try:
    response.raise_for_status()
    result = response.json()
except requests.RequestException as error:
    print(f"Request failed: {error}")
```

When troubleshooting, also review the related request in [**Usage Logs and Costs**](/api-usage/usage-logs-and-costs.md).

***

### 🛠️ Common Problems

| Problem                   | What to Check                                     |
| ------------------------- | ------------------------------------------------- |
| **Authentication failed** | API Token and Bearer header                       |
| **Model not found**       | Exact Model ID and capitalization                 |
| **Invalid request**       | Endpoint and model-specific fields                |
| **Request timed out**     | Increase the client timeout or check task status  |
| **Insufficient balance**  | Current Balance and API Token remaining allowance |

> 🔐 Never provide your full API Token in source code, logs, screenshots, or support messages.

***

### 🚀 Next Steps

Continue with:

* [**cURL**](/sdks-and-migration/curl.md)
* [**API Basics**](/api-guides/api-basics.md)
* [**Chat Completions API**](/api-guides/chat-completions-api.md)
* [**Image Generation API**](/api-guides/image-generation-api.md)
* [**Video Generation API**](/api-guides/video-generation-api.md)
