For the complete documentation index, see llms.txt. Markdown versions of documentation pages are available by appending .md to page URLs.
跳至內容

Python

Learn how to call ApiSmart APIs with Python, including model discovery, Chat Completions, streaming, image generation, local image uploads, and asynchronous video tasks.

Use Python to integrate ApiSmart into backend services, scripts, automation workflows, and AI-powered applications.

This guide uses the popular requests library to demonstrate how to authenticate requests, retrieve available models, generate text and images, and create asynchronous video tasks.

🚀 Before You Start

Make sure you have:

  • Python 3 installed

  • An ApiSmart account

  • An active API Key

  • Sufficient wallet balance for paid requests

Install requests:

pip install requests

🔑 Set Your API Key

Avoid hard-coding your API Key directly in application source code.

Set it as an environment variable instead.

macOS and Linux

export APISMART_API_KEY="your-api-key"

Windows PowerShell

Then read it in Python:

The standard ApiSmart API Base URL is:

Create reusable request headers:

Keep your API Key private and never commit it to a public repository.

🧩 Get Available Models

Before sending a generation request, you can retrieve the current model IDs:

The API returns model entries in data[].

Use:

as the model value in supported API requests.

Model IDs must match exactly. Do not change periods (.), hyphens (-), or version numbers.

For model categories and IDs, see Models and Model IDs.

💬 Chat Completions

Use:

POST /v1/chat/completions

Example:

The model value must be a valid ApiSmart model ID.

For complete request behavior, see Chat Completions API.

🌊 Stream a Text Response

Chat Completions supports streaming by setting:

With Python requests, enable streamed response handling with stream=True:

This example prints streamed data as it arrives.

The exact processing logic you use depends on how your application wants to consume and display the streamed response.

For an overview of ApiSmart response behavior, see Response Modes.

🖼️ Generate an Image

Use:

POST /v1/images/generations

Example:

Image generation is synchronous by default.

A single generation commonly takes approximately 20–40 seconds, and high-resolution or multi-image requests may take longer.

Use a client timeout of at least 90 seconds. The example above uses:

to provide additional time for generation.

🔄 Generate from a Reference Image

Provide a public image URL using image:

Multiple reference images can also be provided as an array where supported.

For image limits and parameters, see Image Generation API.

📤 Upload a Local Image

Local image uploads use:

POST /v1/images/edits

This endpoint uses multipart form data instead of a JSON request body.

Do not manually set:

for multipart file uploads.

The requests library automatically creates the appropriate multipart content type when you use files=.

Each uploaded image must meet the limits documented in Image Generation API.

🎬 Create a Video Task

Video generation is asynchronous.

Create a task with:

POST /v1/video/tasks

Example:

Save the task ID returned by the API so that you can query the generation status.

For models where resolution and duration affect billing, explicitly provide these values instead of relying on defaults.

🔄 Query a Video Task

Use:

GET /v1/video/tasks/{id}

Example:

Possible task statuses include:

  • queued

  • running

  • succeeded

  • failed

  • cancelled

  • expired

⏳ Poll Until Video Generation Completes

You can poll the task until it reaches a final state:

This example waits 5 seconds between status checks.

For complete HappyHorse and Seedance workflows, see Video Generation API.

🕘 Retrieve Recent Generated Images

Use:

GET /v1/images

🕘 Retrieve Recent Generated Videos

Use:

GET /v1/videos

For history fields and availability limits, see Generated Media History.

⚠️ Handle API Errors

Use raise_for_status() to detect unsuccessful HTTP responses:

Common API responses include:

Status
Example Code
Meaning

400

invalid_request_error

Invalid request

401

invalid_api_key

Invalid API Key

402

insufficient_quota

Insufficient balance

403

model_not_allowed

Model is not available to the API Key

429

rate_limit_error

Request rate limit exceeded

502 / 504

Gateway errors

Temporary upstream or network problem

503

Service unavailable

Provider or dependent service temporarily unavailable

For complete error handling guidance, see HTTP Status Codes and API Errors.

🔁 Retry Temporary Failures

Some 5xx errors may be temporary.

When retrying temporary failures:

  • Add a delay between attempts

  • Use exponential backoff for repeated retries

  • Follow Retry-After when the API provides it

  • Do not automatically retry invalid parameters or authentication errors without fixing the request

A simple retry structure can look like:

Adapt retry behavior to the endpoint and your application's requirements.

✅ Python Integration Checklist

Before deploying your integration, verify that:

  • Your API Key is stored securely

  • The Base URL is correct

  • Model IDs are copied exactly

  • JSON requests use the correct headers

  • Multipart uploads do not force application/json

  • Image requests use an appropriate timeout

  • Video requests store and poll the returned task ID

  • Temporary errors use an appropriate retry strategy

  • Your account has sufficient wallet balance

➡️ Next Steps

Continue with:

最後更新於

這有幫助嗎?