API Reference
Common conventions
Base URL
All endpoints are served under the /v1 prefix.
Authentication
Calls to /v1/* endpoints use API Key authentication (not JWT). The API Key is passed via the following header:
| Header | Format | Description |
|---|---|---|
Authorization | Bearer <api_key> | OpenAI-style. The Anthropic-compatible endpoint also accepts x-api-key with anthropic-version: 2023-06-01. |
Missing or invalid keys return 401.
Balance pre-check
All model-calling endpoints run a balance pre-check before execution:
- Insufficient balance returns
Insufficient credit, mapped to:- OpenAI protocol: HTTP
400,code = insufficient_quota - Anthropic protocol: HTTP
402,type = billing_error
- OpenAI protocol: HTTP
- Some endpoints also estimate a minimum cost per model for a second pre-check.
Create Chat CompletionPOSThttps://api.basicrouter.ai/api/v1/chat/completions
OpenAI Chat Completions-compatible endpoint. Supports streaming and non-streaming, tool calls, JSON mode, and multimodal input.
| Field | Type | Required | Description |
|---|---|---|---|
model | String | Yes | Model name. |
messages | Message[] | Yes | Conversation messages. |
stream | Boolean | No | Stream mode, default false. |
temperature | Double | No | Sampling temperature. |
max_tokens | Integer | No | Maximum output tokens. |
top_p | Double | No | Nucleus sampling. |
presence_penalty | Double | No | — |
frequency_penalty | Double | No | — |
tools | Tool[] | No | Tool definitions. |
tool_choice | String|Object | No | auto / none / required / specific function. |
response_format | Object | No | {type, json_schema:{name,schema,strict}}; text/json_object/json_schema. |
parallel_tool_calls | Boolean | No | — |
metadata | Map | No | Pass-through metadata. |
Message fields:
| Field | Type | Description |
|---|---|---|
role | String | system / user / assistant / tool. |
content | String|Array | Plain text or multimodal content block array ([{type:"text",text},{type:"image_url",image_url:{url}}]). |
tool_call_id | String | Links to the tool_calls when role=tool. |
tool_calls | ToolCall[] | Present when role=assistant makes tool calls. |
| Field | Type | Description |
|---|---|---|
type | String | Fixed function. |
function | Object | Function definition. |
function.name | String | Function name. |
function.description | String | Function description. |
function.parameters | Object | JSON Schema for inputs. |
curl --request POST \
--url https://api.basicrouter.ai/api/v1/chat/completions \
--header "Authorization: Bearer $BASICROUTER_API_KEY" \
--header "Content-Type: application/json" \
--data '{
"model": "glm-5.2",
"messages": [{"role": "user", "content": "Describe Hangzhou in one sentence."}],
"stream": false,
"temperature": 0.7
}'{
"id": "chatcmpl-xxx",
"object": "chat.completion",
"created": 1721380000,
"model": "glm-5.2",
"choices": [
{
"index": 0,
"message": {"role": "assistant", "content": "Hangzhou is ..."},
"finish_reason": "stop"
}
],
"usage": {"prompt_tokens": 12, "completion_tokens": 18, "total_tokens": 30}
}Response fields (non-streaming):
| Field | Type | Description |
|---|---|---|
id | String | Completion id. |
object | String | Fixed chat.completion. |
created | Long | Created timestamp (seconds). |
model | String | Model name. |
choices | Choice[] | {index, message:{role, content, tool_calls?}, finish_reason}. |
usage | Object | {prompt_tokens, completion_tokens, total_tokens}. |
| Field | Type | Description |
|---|---|---|
id | String | Tool call id. |
type | String | Fixed function. |
function | Object | Function call details. |
function.name | String | Function name. |
function.arguments | Object | Function arguments. |
Streaming response example:
data: {"object":"chat.completion.chunk","choices":[{"delta":{"role":"assistant","content":"..."}}]}
data: {"object":"chat.completion.chunk","choices":[{"delta":{"content":"..."}}]}
data: [DONE]Create ResponsePOSThttps://api.basicrouter.ai/api/v1/responses
OpenAI Responses-compatible endpoint. Uses input instead of messages, instructions instead of a system message, and a text block instead of response_format.
| Field | Type | Required | Description |
|---|---|---|---|
model | String | Yes | Model name. |
input | String|Array | Yes | Plain string (user message) or message object array. |
instructions | String | No | System prompt. |
stream | Boolean | No | Default false. |
max_output_tokens | Integer | No | Maximum output tokens. |
temperature | Double | No | Default 1. |
top_p | Double | No | — |
tools | Tool[] | No | Top-level {type, name, description, parameters}. |
tool_choice | String|Object | No | auto/none/required/{type,name}. |
text | Object | No | {format:{type, name, schema, strict}}; text/json_object/json_schema. |
metadata | Map | No | — |
previous_response_id | String | No | Previous response id for multi-turn. |
parallel_tool_calls | Boolean | No | — |
curl --request POST \
--url https://api.basicrouter.ai/api/v1/responses \
--header "Authorization: Bearer $BASICROUTER_API_KEY" \
--header "Content-Type: application/json" \
--data '{
"model": "glm-5.2",
"input": "Describe Hangzhou in one sentence.",
"instructions": "Be concise.",
"stream": false
}'{
"id": "resp_xxx",
"object": "response",
"model": "glm-5.2",
"status": "completed",
"created_at": 1721380000,
"output": [
{
"id": "msg_xxx",
"type": "message",
"role": "assistant",
"content": [{"type": "output_text", "text": "Hangzhou is ..."}],
"status": "completed"
}
],
"usage": {"input_tokens": 12, "output_tokens": 18, "total_tokens": 30}
}Response fields (non-streaming):
| Field | Type | Description |
|---|---|---|
id | String | Response id. |
object | String | Fixed response. |
model | String | Model name. |
status | String | e.g. completed. |
created_at | Long | Created timestamp (seconds). |
output | Array | Output items. Message items: {id, type:"message", role, content:[{type:"output_text", text}], status}. Tool-call items: {type:"function_call", id, name, call_id, arguments, status}. |
usage | Object | {input_tokens, output_tokens, total_tokens}. For Claude models, input_tokens includes cache_read and output_tokens includes cache_write. |
Streaming follows the Responses API events:
| Event | Description |
|---|---|
response.created | Start of the response stream. |
response.output_text.delta | Incremental text output update. |
response.completed | End of the response stream. |
Create Anthropic MessagePOSThttps://api.basicrouter.ai/api/v1/messages
Anthropic Messages-compatible endpoint. Accepts x-api-key and anthropic-version: 2023-06-01 headers. Content blocks support text, image, tool_use, tool_result, thinking, and redacted_thinking.
| Field | Type | Required | JSON field | Description |
|---|---|---|---|---|
model | String | Yes | model | Model name. |
messages | Message[] | Yes | messages | Conversation messages. |
system | String|Array | No | system | System prompt, string or [{type,text}]. |
maxTokens | Integer | Yes | max_tokens | Maximum output tokens. |
stream | Boolean | No | stream | Streaming. |
temperature | Double | No | temperature | — |
topP | Double | No | top_p | — |
topK | Integer | No | top_k | — |
tools | Tool[] | No | tools | Tool definitions (input_schema). |
toolChoice | Object | No | tool_choice | — |
metadata | Map | No | metadata | — |
thinking | Object | No | thinking | Extended thinking config. |
stopSequences | Object | No | stop_sequences | — |
anthropicBeta | Object | No | anthropic_beta | Beta feature header. |
| Field | Type | Description |
|---|---|---|
role | String | Message role, e.g. user / assistant. |
content | String|ContentBlock[] | Plain text or an array of content blocks. |
| Field | Type | Description |
|---|---|---|
type | String | One of text, image, tool_use, tool_result, thinking, redacted_thinking. |
text | String | Present when type is text. |
source | Object | Present when type is image. |
Examples:
{ "type": "image", "source": { "type": "base64", "media_type": "...", "data": "..." } }
{ "type": "image", "source": { "type": "url", "url": "..." } }| Field | Type | Description |
|---|---|---|
name | String | Function name. |
description | String | Function description. |
input_schema | Object | JSON Schema for inputs. |
cache_control | Object | Optional cache control. |
curl --request POST \
--url https://api.basicrouter.ai/api/v1/messages \
--header "Authorization: Bearer $BASICROUTER_API_KEY" \
--header "anthropic-version: 2023-06-01" \
--header "Content-Type: application/json" \
--data '{
"model": "claude-sonnet-4.6",
"max_tokens": 1024,
"messages": [{"role": "user", "content": "Describe Hangzhou in one sentence."}]
}'{
"id": "msg_xxx",
"type": "message",
"role": "assistant",
"model": "claude-sonnet-4.6",
"content": [{"type": "text", "text": "Hangzhou is ..."}],
"stop_reason": "end_turn",
"usage": {"input_tokens": 12, "output_tokens": 18}
}Response fields (non-streaming):
| Field | Type | Description |
|---|---|---|
id | String | Message id. |
type | String | Fixed message. |
role | String | Fixed assistant. |
model | String | Model name. |
content | ContentBlock[] | Response content blocks (e.g. {type:"text", text}, {type:"tool_use", ...}). |
stop_reason | String | e.g. end_turn, tool_use, max_tokens. |
usage | Object | {input_tokens, output_tokens}. |
| Event | Description |
|---|---|
message_start | Start of the message stream. |
content_block_start | Start of a new content block. |
content_block_delta | Incremental update for a content block. |
content_block_stop | End of a content block. |
message_delta | Incremental update for the message. |
message_stop | End of the message stream. |
List ModelsGEThttps://api.basicrouter.ai/api/v1/models
Returns all online, enabled API models.
curl --request GET \
--url https://api.basicrouter.ai/api/v1/models \
--header "Authorization: Bearer $BASICROUTER_API_KEY"{
"object": "list",
"data": [
{
"id": "glm-5.2",
"object": "model",
"display_name": "glm-5.2",
"created": 1721380000,
"owned_by": "Zai",
"input_modalities": ["text", "image"],
"output_modalities": ["text"],
"context_length": 128000,
"description": "..."
}
]
}Each model entry (data[]) fields:
| Field | Type | Description |
|---|---|---|
id | String | Model id. |
object | String | Fixed model. |
display_name | String | Display name. |
created | Long | Created timestamp (seconds). |
owned_by | String | Owner / vendor. |
input_modalities | String[] | e.g. ["text","image"]. |
output_modalities | String[] | e.g. ["text"]. |
context_length | Integer | Maximum context length. |
description | String | Model description. |
Retrieve ModelGEThttps://api.basicrouter.ai/api/v1/models/{model}
Returns a single model with the same shape as a list entry. Returns HTTP 404 when the model does not exist.
curl --request GET \
--url https://api.basicrouter.ai/api/v1/models/gpt-5.5 \
--header "Authorization: Bearer $BASICROUTER_API_KEY"Success response: a single model object with the same fields as a /v1/models list entry.
When the model does not exist, returns HTTP 404:
{"error": {"message": "The model 'xxx' does not exist", "type": "invalid_request_error", "code": "invalid_model_error"}}List Image ModelsGEThttps://api.basicrouter.ai/api/v1/image-models
Query the resolutions, ratios, and maximum counts supported by an image model before calling /v1/image-generations. No authentication required.
| Field | Type | Description |
|---|---|---|
id | String | Model id. |
object | String | Fixed image_model. |
displayName | String | Display name. |
description | String | Model description. |
icon | String | Icon URL. |
created | Long | Created timestamp (seconds). |
maxCount | Integer | Max images per request. |
fileMax | Integer | Max reference images. When 0, image-to-image is not supported. |
resolutions | String[] | Supported resolutions, e.g. ["720p","1080p"]. |
ratios | String[] | Supported aspect ratios, e.g. ["1:1","3:2"]. |
curl --request GET \
--url https://api.basicrouter.ai/api/v1/image-models \
--header "Authorization: Bearer $BASICROUTER_API_KEY"{
"object": "list",
"data": [
{
"id": "gpt-image-2",
"object": "image_model",
"displayName": "GPT Image 1",
"description": "...",
"icon": "...",
"created": 1721380000,
"maxCount": 4,
"fileMax": 10,
"resolutions": ["720p", "1080p"],
"ratios": ["1:1", "3:2"]
}
]
}List Video ModelsGEThttps://api.basicrouter.ai/api/v1/video-models
Query the supported videoType values, duration range, resolutions, and ratios for a video model before calling /v1/video-generations. No authentication required.
| Field | Type | Description |
|---|---|---|
id | String | Model id. |
object | String | Fixed video_model. |
displayName | String | Display name. |
description | String | Model description. |
icon | String | Icon URL. |
created | Long | Created timestamp (seconds). |
allowedVideoTypes | VideoTypeOption[] | Supported videoType list. |
videoDurationMin | Integer | Minimum seconds per clip. |
videoDurationMax | Integer | Maximum seconds per clip. |
videoDurationSuggest | Integer[] | Recommended duration steps, e.g. [5,8,10]. |
resolutions | String[] | Supported resolutions. |
ratios | String[] | Supported aspect ratios. |
resolutionOptions | ResolutionOption[] | Structured resolution+ratio+size combos. |
fileMax | Integer | Max reference assets. |
VideoTypeOption fields:
| Field | Type | Description |
|---|---|---|
code | Integer | The videoType value to pass to /v1/video-generations. |
name | String | Localized type name (text-to-video / image-to-video / ...). |
curl --request GET \
--url https://api.basicrouter.ai/api/v1/video-models \
--header "Authorization: Bearer $BASICROUTER_API_KEY"{
"object": "list",
"data": [
{
"id": "sora-2",
"object": "video_model",
"displayName": "Sora 2",
"description": "...",
"icon": "...",
"created": 1721380000,
"allowedVideoTypes": [
{"code": 1, "name": "text-to-video"},
{"code": 2, "name": "image-to-video"},
{"code": 3, "name": "image-to-video (first/last frame)"}
],
"videoDurationMin": 5,
"videoDurationMax": 10,
"videoDurationSuggest": [5, 8, 10],
"resolutions": ["1080p", "720p"],
"ratios": ["16:9", "9:16"],
"fileMax": 5
}
]
}Price tier fields
The four model query endpoints /v1/models, /v1/models/{model}, /v1/image-models, and /v1/video-models return the effective billing price for the current caller (API key user), fully consistent with actual charges, and return all price tiers of the model.
Field naming difference: /v1/models and /v1/models/{model} use OpenAI-style snake_case (price_tiers); /v1/image-models and /v1/video-models use camelCase (priceTiers). The structures are identical.
price_tiers / priceTiers is an array; each element is a price tier:
| Field | Type | Description |
|---|---|---|
outputPrice | decimal | Effective output unit price for the current caller |
cachePrice | decimal | Cache price (general models, used by the legacy billing formula) |
cacheReadPrice | decimal | Cache read unit price (Bedrock Claude only) |
cacheWritePrice | decimal | Cache write unit price (Bedrock Claude only) |
ratio | decimal | Billing multiplier. FIXED mode is 1; RATIO mode is the user/group multiplier |
mode | string | Pricing mode: RATIO / FIXED |
planId | string | Matched pricing plan ID, may be null |
The three model types share the same structure; only the descriptive field values differ. Non-applicable fields are null:
| Model type | UNIT | Effective description fields |
|---|---|---|
| Text | token | region / bandMin / bandMax |
| Image | image | resolution / clarity |
| Video | video | resolution / clarity |
Price meaning: the returned inputPrice / outputPrice / cacheReadPrice / cacheWritePrice values are the final billing unit prices for the current API key user after step-by-step resolution through the price chain (chain)→ guidance → base price, consistent with actual charges. The unit price seen by callers differs based on their pricing chain (reseller / distributor / enterprise / user-level configuration).
Actual deduction = usage ÷ quantity × corresponding unit price × ratio. For per-second video billing: actual deduction = duration × outputPrice × ratio.
Boundary & exception handling (read-only endpoints will not return 500 due to price configuration issues)
| Scenario | Behavior |
|---|---|
| Single tier parse failure (pricing policy denies access, config missing) | Skip that tier, log a warning, and continue parsing remaining tiers |
| All tiers of a model fail to parse | Empty array [], model still returned normally |
| Model has no price configuration | Empty array [] |
| Price parsing throws an uncaught exception | Overall try-catch, return empty array, endpoint still returns 200 |
Response example (/v1/models, text model):
{
"object": "list",
"data": [
{
"id": "gpt-4o",
"object": "model",
"display_name": "gpt-4o",
"context_length": 128000,
"price_tiers": [
{
"region": "GLOBAL",
"bandMin": null,
"bandMax": null,
"resolution": null,
"clarity": null,
"unit": "token",
"quantity": 1000,
"description": "per 1k tokens",
"inputPrice": 0.0025,
"outputPrice": 0.01,
"cachePrice": 0.00125,
"cacheReadPrice": 0,
"cacheWritePrice": 0,
"ratio": 1,
"mode": "RATIO",
"planId": null
}
]
}
]
}Response example (/v1/image-models, image model; priceTiers structure is the same, unit is image):
{
"object": "list",
"data": [
{
"id": "dall-e-3",
"object": "image_model",
"displayName": "dall-e-3",
"resolutions": ["1024x1024", "1792x1024", "1024x1792"],
"priceTiers": [
{
"region": null,
"bandMin": null,
"bandMax": null,
"resolution": "1024x1024",
"clarity": "standard",
"unit": "image",
"quantity": 1,
"description": "per image",
"inputPrice": 0,
"outputPrice": 0.04,
"cachePrice": 0,
"cacheReadPrice": 0,
"cacheWritePrice": 0,
"ratio": 1,
"mode": "RATIO",
"planId": null
}
]
}
]
}Create Image GenerationPOSThttps://api.basicrouter.ai/api/v1/image-generations
Asynchronously submit an image generation task. Returns a taskId immediately; retrieve the result by polling GET /v1/image-generations/{taskId} or via a callbackUrl webhook.
The model, supported resolution / ratio values, count upper limit, and reference-image upload limit (fileMax) must be obtained from GET /v1/image-models first. Only values advertised by that model's spec are accepted.
| Field | Type | Required | Description |
|---|---|---|---|
text | String | Yes | Prompt. |
model | String | Yes | Model name. |
imageUrls | String[] | No | Reference image URLs (image-to-image). |
count | Integer | No | Number of images (≥0). |
resolution | String | No | Resolution (see /v1/image-models). |
ratio | String | No | Aspect ratio. |
callbackUrl | String | No | Task-level webhook URL. |
curl --request POST \
--url https://api.basicrouter.ai/api/v1/image-generations \
--header "Authorization: Bearer $BASICROUTER_API_KEY" \
--header "Content-Type: application/json" \
--data '{
"model": "seedream-4.5",
"text": "A cat drinking water by the river",
"count": 1,
"resolution": "2k",
"ratio": "1:1",
"imageUrls": []
}'{
"code": 200,
"message": "image task is commit",
"data": {"taskId": "img_xxx"}
}Error responses:
// Insufficient credit
{ "code": 500, "message": "Insufficient credit" }
// Model not found
{ "code": 404, "message": "Model not found: xxx" }Retrieve Image GenerationGEThttps://api.basicrouter.ai/api/v1/image-generations/{taskId}
Poll an image generation task. status is pending / success / failed. images is a JSON-stringified array of image URLs; text carries any model-attached text description (e.g. Gemini multimodal output), null otherwise.
curl --request GET \
--url https://api.basicrouter.ai/api/v1/image-generations/img_xxx \
--header "Authorization: Bearer $BASICROUTER_API_KEY"{
"code": 200,
"message": "success",
"data": {
"taskId": "img_xxx",
"status": "success",
"errorMessage": null,
"images": "[\"https://.../1.png\"]",
"text": null
}
}Response data fields:
| Field | Type | Description |
|---|---|---|
taskId | String | Task id. |
status | String | pending / success / failed. |
errorMessage | String | Failure reason, null on success. |
images | String | JSON-stringified array of image URLs, e.g. "[\"https://.../1.png\"]". |
text | String | Model-attached text description (e.g. Gemini multimodal output); null otherwise. |
Task not found:
{ "code": 500, "message": "task not found" }If callbackUrl was supplied on submit, the server pushes the final success / failed result via webhook with the same data shape.
Complete example (submit + poll)
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
public class ImageGenerationExample {
private static final String BASE = "https://api.basicrouter.ai/api/v1";
private static final String API_KEY = System.getenv("BASICROUTER_API_KEY");
public static void main(String[] args) throws Exception {
HttpClient http = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(10)).build();
// 1. Submit the task.
String body = "{"
+ "\"model\":\"seedream-4.5\","
+ "\"text\":\"A cat drinking water by the river\","
+ "\"count\":1,"
+ "\"resolution\":\"2k\","
+ "\"ratio\":\"1:1\","
+ "\"imageUrls\":[]"
+ "}";
HttpResponse<String> submit = http.send(
HttpRequest.newBuilder(URI.create(BASE + "/image-generations"))
.header("Authorization", "Bearer " + API_KEY)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(body)).build(),
HttpResponse.BodyHandlers.ofString());
String taskId = extract(submit.body(), "taskId");
System.out.println("taskId = " + taskId);
// 2. Poll until terminal status.
String status = "pending";
while ("pending".equals(status)) {
Thread.sleep(15_000L);
HttpResponse<String> poll = http.send(
HttpRequest.newBuilder(URI.create(BASE + "/image-generations/" + taskId))
.header("Authorization", "Bearer " + API_KEY).GET().build(),
HttpResponse.BodyHandlers.ofString());
status = extract(poll.body(), "status");
System.out.println("status = " + status);
}
if (!"success".equals(status)) {
throw new RuntimeException("image generation failed: " + status);
}
// images is a JSON-stringified array of URLs.
String images = extract(pollResult(http, taskId), "images");
System.out.println("images = " + images);
}
// Minimal JSON field extractor — use Jackson/Gson in production.
private static String extract(String json, String field) {
int i = json.indexOf("\"" + field + "\":");
if (i < 0) return null;
i += field.length() + 3;
if (json.charAt(i) == '\"') {
int end = json.indexOf('\"', i + 1);
return json.substring(i + 1, end);
}
int end = i;
while (end < json.length() && "0123456789.".indexOf(json.charAt(end)) >= 0) end++;
return json.substring(i, end);
}
private static String pollResult(HttpClient http, String taskId) throws Exception {
return http.send(HttpRequest.newBuilder(URI.create(BASE + "/image-generations/" + taskId))
.header("Authorization", "Bearer " + API_KEY).GET().build(),
HttpResponse.BodyHandlers.ofString()).body();
}
}import os
import time
import requests
BASE = "https://api.basicrouter.ai/api/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['BASICROUTER_API_KEY']}"}
# 1. Submit the task.
resp = requests.post(
f"{BASE}/image-generations",
headers={**HEADERS, "Content-Type": "application/json"},
json={
"model": "seedream-4.5",
"text": "A cat drinking water by the river",
"count": 1,
"resolution": "2k",
"ratio": "1:1",
"imageUrls": [],
},
)
resp.raise_for_status()
task_id = resp.json()["data"]["taskId"]
print(f"taskId = {task_id}")
# 2. Poll until terminal status.
while True:
time.sleep(15)
poll = requests.get(f"{BASE}/image-generations/{task_id}", headers=HEADERS)
poll.raise_for_status()
data = poll.json()["data"]
status = data["status"]
print(f"status = {status}")
if status != "pending":
break
if status != "success":
raise RuntimeError(f"image generation failed: {data.get('errorMessage')}")
# images is a JSON-stringified array of URLs.
import json
images = json.loads(data["images"])
print(f"images = {images}")Create Video GenerationPOSThttps://api.basicrouter.ai/api/v1/video-generations
Asynchronously submit a video generation task. Returns a taskId immediately; retrieve the result by polling GET /v1/video-generations/{taskId} or via a callbackUrl webhook.
The model, allowed videoType values, duration range (videoDurationMin/Max), supported resolution / ratio, and reference-asset upload limit (fileMax) must be obtained from GET /v1/video-models first. Only videoType codes listed in that model's allowedVideoTypes are accepted.
| Field | Type | Required | Description |
|---|---|---|---|
text | String | Yes | Prompt. |
model | String | Yes | Model name. |
videoType | Integer | Yes | 1 text-to-video / 2 image-to-video (first frame) / 3 image-to-video (first+last frame) / 4 image-to-video (reference) / 5 all reference. |
imageUrls | String[] | No | Image asset URLs. |
videoUrls | VideoUrl[]|String[] | No | Video asset URLs. |
audioUrls | String[] | No | Audio asset URLs. |
resolution | String | No | Resolution. |
ratio | String | No | Aspect ratio. |
duration | Long | No | Seconds (>0). |
callbackUrl | String | No | Task-level webhook URL. |
Examples for each videoType:
1. Text to video (videoType=1)
Generate a video from a text prompt only; no reference assets needed.
curl --request POST \
--url https://api.basicrouter.ai/api/v1/video-generations \
--header "Authorization: Bearer $BASICROUTER_API_KEY" \
--header "Content-Type: application/json" \
--data '{
"videoType": 1,
"text": "A cat jumping on a bed",
"resolution": "480p",
"ratio": "16:9",
"duration": 4,
"model": "seedance-2.0"
}'2. Image to video - first frame (videoType=2)
Provide a single starting frame in imageUrls; the model generates a video starting from that frame.
curl --request POST \
--url https://api.basicrouter.ai/api/v1/video-generations \
--header "Authorization: Bearer $BASICROUTER_API_KEY" \
--header "Content-Type: application/json" \
--data '{
"videoType": 2,
"text": "Happily shaking head",
"resolution": "480p",
"ratio": "16:9",
"duration": 4,
"model": "seedance-2.0",
"imageUrls": ["https://basicrouter-flie.oss-accelerate.aliyuncs.com/test/first-frame.png"]
}'3. Image to video - first and last frame (videoType=3)
Provide both the first and last frame in imageUrls (order: [first, last]); the model generates a transition video between the two frames.
curl --request POST \
--url https://api.basicrouter.ai/api/v1/video-generations \
--header "Authorization: Bearer $BASICROUTER_API_KEY" \
--header "Content-Type: application/json" \
--data '{
"videoType": 3,
"text": "Put on the hat",
"resolution": "480p",
"ratio": "16:9",
"duration": 4,
"model": "seedance-2.0",
"imageUrls": [
"https://basicrouter-flie.oss-accelerate.aliyuncs.com/test/first-frame.png",
"https://basicrouter-flie.oss-accelerate.aliyuncs.com/test/last-frame.png"
]
}'4. Image to video - reference (videoType=4)
Provide one or more reference images in imageUrls; the model uses their style/content as reference (not as a forced first/last frame) to generate the video.
curl --request POST \
--url https://api.basicrouter.ai/api/v1/video-generations \
--header "Authorization: Bearer $BASICROUTER_API_KEY" \
--header "Content-Type: application/json" \
--data '{
"videoType": 4,
"text": "Two cats playing together",
"resolution": "480p",
"ratio": "16:9",
"duration": 4,
"model": "kling-v3-omni-video",
"imageUrls": [
"https://basicrouter-flie.oss-accelerate.aliyuncs.com/test/ref-1.png",
"https://basicrouter-flie.oss-accelerate.aliyuncs.com/test/ref-2.png"
]
}'5. All reference (videoType=5)
Mixed image / video / audio references. Reference assets by position in the prompt: the 1st entry in imageUrls is @图片 1, the 1st in videoUrls is @视频 1, the 1st in audioUrls is @音频 1. videoUrls also accepts plain URL strings.
curl --request POST \
--url https://api.basicrouter.ai/api/v1/video-generations \
--header "Authorization: Bearer $BASICROUTER_API_KEY" \
--header "Content-Type: application/json" \
--data '{
"videoType": 5,
"text": "Use the first-person framing of @视频 1 and @音频 1 as background music. First-person tea ad; start frame is @图片 1 ... end frame is @图片 2.",
"model": "seedance-2.0",
"imageUrls": [
"https://ark-project.tos-cn-beijing.volces.com/doc_image/r2v_tea_pic1.jpg",
"https://ark-project.tos-cn-beijing.volces.com/doc_image/r2v_tea_pic2.jpg"
],
"videoUrls": ["https://ark-project.tos-cn-beijing.volces.com/doc_video/r2v_tea_video1.mp4"],
"audioUrls": ["https://ark-project.tos-cn-beijing.volces.com/doc_audio/r2v_tea_audio1.mp3"],
"resolution": "1080p",
"ratio": "16:9",
"duration": 11
}'Submit response (all five types):
{
"code": 200,
"message": "success",
"data": {"taskId": "vid_xxx"}
}Retrieve Video GenerationGEThttps://api.basicrouter.ai/api/v1/video-generations/{taskId}
Poll a video generation task. status is pending / success / failed; videoUrl is the generated video URL and lastFrameUrl is the last-frame URL (image-to-video scenarios).
curl --request GET \
--url https://api.basicrouter.ai/api/v1/video-generations/vid_xxx \
--header "Authorization: Bearer $BASICROUTER_API_KEY"{
"code": 200,
"message": "success",
"data": {
"status": "success",
"videoUrl": "https://.../out.mp4",
"lastFrameUrl": null,
"message": null
}
}Response data fields:
| Field | Type | Description |
|---|---|---|
status | String | pending / success / failed. |
videoUrl | String | Generated video URL. |
lastFrameUrl | String | Last-frame URL (image-to-video scenarios); null otherwise. |
message | String | Failure reason, null on success. |
If callbackUrl was supplied on submit, the server pushes the final result via webhook with the same data shape.
Complete example (submit + poll)
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
public class VideoGenerationExample {
private static final String BASE = "https://api.basicrouter.ai/api/v1";
private static final String API_KEY = System.getenv("BASICROUTER_API_KEY");
public static void main(String[] args) throws Exception {
HttpClient http = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(10)).build();
// 1. Submit the task (videoType=1: text-to-video).
String body = "{"
+ "\"videoType\":1,"
+ "\"text\":\"A cat jumping on a bed\","
+ "\"resolution\":\"480p\","
+ "\"ratio\":\"16:9\","
+ "\"duration\":4,"
+ "\"model\":\"seedance-2.0\""
+ "}";
HttpResponse<String> submit = http.send(
HttpRequest.newBuilder(URI.create(BASE + "/video-generations"))
.header("Authorization", "Bearer " + API_KEY)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(body)).build(),
HttpResponse.BodyHandlers.ofString());
String taskId = extract(submit.body(), "taskId");
System.out.println("taskId = " + taskId);
// 2. Poll until terminal status. Video tasks take longer — poll every 20s.
String status = "pending";
String lastBody = null;
while ("pending".equals(status)) {
Thread.sleep(20_000L);
HttpResponse<String> poll = http.send(
HttpRequest.newBuilder(URI.create(BASE + "/video-generations/" + taskId))
.header("Authorization", "Bearer " + API_KEY).GET().build(),
HttpResponse.BodyHandlers.ofString());
lastBody = poll.body();
status = extract(lastBody, "status");
System.out.println("status = " + status);
}
if (!"success".equals(status)) {
throw new RuntimeException("video generation failed: " + status);
}
String videoUrl = extract(lastBody, "videoUrl");
System.out.println("videoUrl = " + videoUrl);
}
// Minimal JSON field extractor — use Jackson/Gson in production.
private static String extract(String json, String field) {
int i = json.indexOf("\"" + field + "\":");
if (i < 0) return null;
i += field.length() + 3;
if (json.charAt(i) == '\"') {
int end = json.indexOf('\"', i + 1);
return json.substring(i + 1, end);
}
int end = i;
while (end < json.length() && "0123456789.".indexOf(json.charAt(end)) >= 0) end++;
return json.substring(i, end);
}
}import os
import time
import requests
BASE = "https://api.basicrouter.ai/api/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['BASICROUTER_API_KEY']}"}
# 1. Submit the task (videoType=1: text-to-video).
resp = requests.post(
f"{BASE}/video-generations",
headers={**HEADERS, "Content-Type": "application/json"},
json={
"videoType": 1,
"text": "A cat jumping on a bed",
"resolution": "480p",
"ratio": "16:9",
"duration": 4,
"model": "seedance-2.0",
},
)
resp.raise_for_status()
task_id = resp.json()["data"]["taskId"]
print(f"taskId = {task_id}")
# 2. Poll until terminal status. Video tasks take longer — poll every 20s.
while True:
time.sleep(20)
poll = requests.get(f"{BASE}/video-generations/{task_id}", headers=HEADERS)
poll.raise_for_status()
data = poll.json()["data"]
status = data["status"]
print(f"status = {status}")
if status != "pending":
break
if status != "success":
raise RuntimeError(f"video generation failed: {data.get('message')}")
print(f"videoUrl = {data['videoUrl']}")
if data.get("lastFrameUrl"):
print(f"lastFrameUrl = {data['lastFrameUrl']}")Retrieve Billing BalanceGEThttps://api.basicrouter.ai/api/v1/billing/balance
Returns the account balance split into three wallets: monthly plan, resource packs, and pay-as-you-go credit.
curl --request GET \
--url https://api.basicrouter.ai/api/v1/billing/balance \
--header "Authorization: Bearer $BASICROUTER_API_KEY"{
"totalCredit": 128.50,
"totalResourceCredit": 30.00,
"wallets": {
"monthlyPlan": {"id": "pkg_xxx", "credit": 50.00, "name": "Monthly plan"},
"resourcePacks": [
{"id": "rp_xxx", "credit": 30.00, "name": "Video resource pack"}
],
"payAsYouGo": 48.50
}
}Response fields:
| Field | Type | Description |
|---|---|---|
totalCredit | BigDecimal | Total balance. |
totalResourceCredit | BigDecimal | Sum of resource-pack balances. |
wallets.monthlyPlan | WalletDetail | Monthly plan (null if none). |
wallets.resourcePacks | WalletDetail[] | Resource pack list. |
wallets.payAsYouGo | BigDecimal | Pay-as-you-go balance. |
WalletDetailVO fields::
| Field | Type | Description |
|---|---|---|
id | String | Wallet id. |
credit | BigDecimal | Balance credits. |
name | String | Wallet name. |
List UsageGEThttps://api.basicrouter.ai/api/v1/usage
Paginated model-call billing details, snapshoted by price (priceSnapshotId), ordered by order creation time descending. Only normal charge records (reason = model usage) are returned.
Query parameters:
| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
page | Integer | No | 1 | Page number, 1-based. |
size | Integer | No | 20 | Page size (paginated by priceSnapshotId). |
startTime | LocalDateTime | No | — | Start time, format yyyy-MM-ddTHH:mm:ss, filters by snapshot orderCreatedAt. |
endTime | LocalDateTime | No | — | End time, format yyyy-MM-ddTHH:mm:ss. |
curl --request GET \
--url "https://api.basicrouter.ai/api/v1/usage?page=1&size=20&startTime=2026-07-01T00:00:00&endTime=2026-07-31T23:59:59" \
--header "Authorization: Bearer $BASICROUTER_API_KEY"Response wrapper:
{
"code": 0,
"message": "success",
"data": { ... }
}| Field | Type | Description |
|---|---|---|
records | UsageDetailVO[] | Current page records. |
total | Long | Total count. |
current | Long | Current page. |
size | Long | Page size. |
pages | Long | Total pages. |
UsageDetailVO fields:
| Field | Type | Description |
|---|---|---|
priceSnapshotId | String | Price snapshot id. |
taskId | String | Task id. |
credit | BigDecimal | Charged amount. |
model | String | Model name. |
modelType | String | text / image / video. |
inputTokens | Long | Input tokens; null for image/video. |
outputTokens | Long | Output tokens. |
totalTokens | Long | Total tokens. |
cacheReadTokens | Long | Cache-read tokens. |
cacheWriteTokens | Long | Cache-write tokens. |
imageCount | Integer | Image count; set for image models. |
imageResolution | String | Image resolution, e.g. 720P. |
imageRatio | String | Image aspect ratio, e.g. 1:1. |
videoResolution | String | Video resolution, e.g. 1080p. |
videoRatio | String | Video aspect ratio, e.g. 16:9. |
videoDurationSec | Long | Video duration in seconds. |
orderCreatedAt | LocalDateTime | Order creation time (snapshot orderCreatedAt). |
creditDetails | CreditDetailItem[] | Order details under this snapshot (from credit_order_t). |
CreditDetailItem fields:
| Field | Type | Description |
|---|---|---|
credit | BigDecimal | Amount charged by this order. |
deductionSource | String | Deduction source (Balance / Monthly Package / Resource Package). |
packageName | String | Package name; null if no package. |
Null-value convention: only the fields relevant to each modelType are populated; the rest are null. text populates the token fields; image populates imageCount/imageResolution/imageRatio; video populates videoResolution/videoRatio/videoDurationSec.
Response example:
{
"code": 200,
"message": "success",
"data": {
"records": [
{
"priceSnapshotId": "snap_9f3c1a2b",
"taskId": "task_5e8a1c33",
"credit": 0.0342,
"model": "glm-5.2",
"modelType": "text",
"inputTokens": 1280,
"outputTokens": 642,
"totalTokens": 1922,
"cacheReadTokens": 0,
"cacheWriteTokens": 0,
"imageCount": null,
"imageResolution": null,
"imageRatio": null,
"videoResolution": null,
"videoRatio": null,
"videoDurationSec": null,
"orderCreatedAt": "2026-07-18T14:23:11",
"creditDetails": [
{
"credit": 0.0342,
"deductionSource": "balance",
"packageName": ""
}
]
},
{
"priceSnapshotId": "snap_a12f77c0",
"taskId": "task_c71e44a2",
"credit": 1.8000,
"model": "seedance-2.0",
"modelType": "video",
"inputTokens": null,
"outputTokens": null,
"totalTokens": null,
"cacheReadTokens": null,
"cacheWriteTokens": null,
"imageCount": null,
"imageResolution": null,
"imageRatio": null,
"videoResolution": "1080p",
"videoRatio": "16:9",
"videoDurationSec": 8,
"orderCreatedAt": "2026-07-17T22:41:09",
"creditDetails": [
{
"credit": 1.5000,
"deductionSource": "Monthly Package",
"packageName": "基础月度套餐"
},
{
"credit": 0.3000,
"deductionSource": "Resource Package",
"packageName": "byteplus视频资源包"
}
]
}
],
"total": 128,
"current": 1,
"size": 20,
"pages": 7
}
}List Billing TransactionsGEThttps://api.basicrouter.ai/api/v1/billing/transactions
Paginated list of the current user's paid (status=2) recharge transactions, ordered by created_at descending.
| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
page | Integer | No | 1 | Page number. |
size | Integer | No | 20 | Page size. |
startTime | String | No | — | Start time, yyyy-MM-dd HH:mm:ss, inclusive. |
endTime | String | No | — | End time, yyyy-MM-dd HH:mm:ss, inclusive. |
curl --request GET \
--url "https://api.basicrouter.ai/api/v1/billing/transactions?page=1&size=20&startTime=2026-07-01%2000:00:00&endTime=2026-07-31%2023:59:59" \
--header "Authorization: Bearer $BASICROUTER_API_KEY"Response wrapper:
{
"code": 0,
"message": "success",
"data": { ... }
}| Field | Type | Description |
|---|---|---|
records | TransactionVO[] | Current page transactions. |
total | Long | Total count. |
current | Long | Current page. |
size | Long | Page size. |
pages | Long | Total pages. |
TransactionVO fields:
| Field | Type | Description |
|---|---|---|
orderNo | String | Order number. |
thirdPartyOrderNo | String | Third-party order number. |
amount | BigDecimal | Order amount. |
actualAmount | BigDecimal | Actually paid amount. |
discount | BigDecimal | Discount amount. |
paymentMethod | String | Payment method (wechat / alipay / ustd / stripe / wallyt etc.). |
TransactionVO fields:
| Field | Type | Description |
|---|---|---|
serviceFeeAmount | BigDecimal | Service fee amount. |
paymentChannel | String | Payment platform. |
source | String | Order source (recharge / package_purchase etc.). |
packageName | String | Package name (set for package purchases; null for plain recharges). |
createdAt | LocalDateTime | Creation time. |
{
"code": 200,
"message": "success",
"data": {
"records": [
{
"orderNo": "R20260718abc123",
"thirdPartyOrderNo": "wx_pay_xxx",
"amount": 50.00,
"actualAmount": 48.50,
"discount": 1.50,
"paymentMethod": "wechat",
"serviceFeeAmount": 0.00,
"paymentChannel": "wechat",
"source": "recharge",
"packageName": null,
"createdAt": "2026-07-18T14:23:11"
}
],
"total": 28,
"current": 1,
"size": 20,
"pages": 2
}
}