API & SDK reference
Request examples, authentication, chat completions, endpoints, native Gemini, image editing, and SDK integration.
Models in examples are illustrative. Check Models and your console for current model availability and capabilities.
Introduction
CanalAPI is a unified gateway over many LLM, image, and audio models. Use any OpenAI-compatible client — point base_url at https://api.canalapi.com/v1, pass your key, and ship.
Quickstart
You need two things: an API key (from the console) and a model slug. Here's the simplest possible request:
cURL
# Any OpenAI-compatible client works — just swap the base URL
curl https://api.canalapi.com/v1/chat/completions \
-H "Authorization: Bearer $CANAL_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "claude-opus-4-6",
"messages": [{"role":"user","content":"Hello"}]
}'python
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.canalapi.com/v1",
api_key=os.environ["CANAL_KEY"],
)
resp = client.chat.completions.create(
model="claude-opus-4-6",
messages=[{"role": "user", "content": "Hello"}],
)
print(resp.choices[0].message.content)typescript
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://api.canalapi.com/v1",
apiKey: process.env.CANAL_KEY,
});
const r = await client.chat.completions.create({
model: "claude-opus-4-6",
messages: [{ role: "user", content: "Hello" }],
});
console.log(r.choices[0].message.content);go
package main
import (
"bytes"
"net/http"
"os"
)
func main() {
body := bytes.NewBufferString(`{
"model": "claude-opus-4-6",
"messages": [{"role":"user","content":"Hello"}]
}`)
req, _ := http.NewRequest("POST",
"https://api.canalapi.com/v1/chat/completions", body)
req.Header.Set("Authorization", "Bearer "+os.Getenv("CANAL_KEY"))
req.Header.Set("Content-Type", "application/json")
resp, _ := http.DefaultClient.Do(req)
defer resp.Body.Close()
}Response
{
"id": "chatcmpl_8K2m3",
"object": "chat.completion",
"created": 1745078400,
"model": "claude-opus-4-6",
"choices": [{
"index": 0,
"message": { "role": "assistant", "content": "Hi there!" },
"finish_reason": "stop"
}],
"usage": { "prompt_tokens": 8, "completion_tokens": 3, "total_tokens": 11 }
}Authentication
Authenticated endpoints accept either Authorization: Bearer <key> (OpenAI-style) or x-api-key: <key> (Anthropic SDK style); Authorization wins when both are present. Keys are prefixed with ca_sk_live_ — create separate keys per environment (dev / staging / prod) from the console.
Set your key in an environment variable (e.g. CANAL_KEY). Any OpenAI-compatible SDK just needs its base URL pointed at https://api.canalapi.com/v1 — no other code change required.
Chat completions
POST /v1/chat/completions
Create a chat completion. Compatible with OpenAI's chat/completions — same parameters, same response shape, with automatic upstream-channel selection.
| Field | Type | required | Description |
|---|---|---|---|
| model | string | required | Model slug. Call /v1/models for the live list, or browse the pricing page. |
| messages | array | required | Conversation as an array of { role, content } objects. Roles: system, user, assistant. |
| stream | boolean | optional | If true, tokens are streamed via SSE. Default false. |
| temperature | number | optional | 0–2. Higher = more random. Default is model-dependent. |
| max_tokens | integer | optional | Cap on completion tokens. Model-dependent default. |
| tools | array | optional | Function-calling tool definitions. Request schema follows OpenAI / Anthropic native shapes. |
Streaming
stream = client.chat.completions.create(
model="claude-opus-4-6",
messages=[{"role": "user", "content": "Write a haiku."}],
stream=True,
)
for chunk in stream:
print(chunk.choices[0].delta.content or "", end="")Endpoints at a glance
All endpoints share the same key and auth scheme. The table below lists the OpenAI-compatible and vendor-native endpoints currently live:
| Method | Path | Purpose |
|---|---|---|
| POST | /v1/embeddings | Text embeddings (OpenAI Embeddings compatible) |
| POST | /v1/images/generations | Image generation (DALL·E compatible; /edits and /variations also live) |
| POST | /v1/audio/transcriptions | Speech-to-text (Whisper compatible; /audio/translations also live) |
| POST | /v1/audio/speech | Text-to-speech (TTS) |
| POST | /v1/moderations | Content moderation (typically free) |
| POST | /v1/responses | OpenAI Responses API compatible endpoint |
| POST | /v1/messages | Anthropic Messages API — native endpoint for the Claude SDK; the count_tokens sub-route is free |
| GET | /v1/models | List available models (public, no auth required) |
| GET | /v1/dashboard/billing/credit_grants | OpenAI-compatible account balance summary |
Request parameters and vendor-specific fields follow the upstream API spec; CanalAPI forwards all standard fields.
Embeddings
Text embeddings (OpenAI Embeddings compatible)
Images
Image generation (DALL·E compatible; /edits and /variations also live)
Audio
Speech-to-text (Whisper compatible; /audio/translations also live)
List models
List available models (public, no auth required)
Native Gemini
Native Gemini uses https://api.canalapi.com/v1beta. Send your CanalAPI key in the Authorization: Bearer or x-goog-api-key header. The ?key= query parameter is not supported.
Generate content
# 把 Gemini SDK 的 base_url 指向 CanalAPI 的 /v1beta,用 CanalAPI 密钥鉴权
curl "https://api.canalapi.com/v1beta/models/gemini-3.1-pro-preview:generateContent" \
-H "x-goog-api-key: $CANAL_KEY" \
-H "Content-Type: application/json" \
-d '{
"contents": [{ "parts": [{ "text": "Hello" }] }]
}'Streaming
# 流式:streamGenerateContent + ?alt=sse;鉴权头同样可用 Authorization: Bearer
curl "https://api.canalapi.com/v1beta/models/gemini-3.1-pro-preview:streamGenerateContent?alt=sse" \
-H "Authorization: Bearer $CANAL_KEY" \
-H "Content-Type: application/json" \
-d '{
"contents": [{ "parts": [{ "text": "Write a haiku." }] }]
}'Gemini SDK
Use @google/genai with httpOptions.baseUrl set to the API origin and apiVersion set to v1beta.
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({
apiKey: process.env.CANAL_KEY,
httpOptions: { baseUrl: 'https://api.canalapi.com', apiVersion: 'v1beta' },
});
const response = await client.models.generateContent({
model: 'gemini-3.1-pro-preview',
contents: 'Hello',
});
console.log(response.text);Google Gen AI SDK — HttpOptions
Image edits
POST /v1/images/edits
Edit an existing image from a prompt (with an optional mask). Requests use multipart/form-data and are compatible with OpenAI Images Edit; billed per generated image.
| Field | Type | required | Description |
|---|---|---|---|
| image | file | required | Source image file to edit (image/jpeg · image/png · image/webp, ≤ 25MB each). |
| prompt | string | required | Text instruction describing the desired edit. |
| mask | file | optional | Optional mask image; transparent areas mark the region to repaint. |
| model | string | optional | Model slug, defaults to dall-e-2. You can also pass an image model such as gpt-image-1. |
| n | integer | optional | Number of images to generate (1–10), default 1. |
| size | string | optional | Output image size, e.g. 1024x1024. |
# multipart/form-data:image + prompt 必填,mask 可选
curl https://api.canalapi.com/v1/images/edits \
-H "Authorization: Bearer $CANAL_KEY" \
-F image="@source.png" \
-F prompt="Add a red hat to the cat" \
-F model="gpt-image-1" \
-F n=1 \
-F size="1024x1024"Image variations
POST /v1/images/variations
Create variations of a source image with no prompt. Also multipart/form-data — only the image field is required (model / n / size optional).
# multipart/form-data:仅需 image
curl https://api.canalapi.com/v1/images/variations \
-H "Authorization: Bearer $CANAL_KEY" \
-F image="@source.png" \
-F n=2 \
-F size="1024x1024"image and mask accept only image/jpeg, image/png, and image/webp, up to 25MB per file.
Errors & retries
| HTTP status | Common meaning | Action |
|---|---|---|
| 400 / 404 | Parameter, endpoint, or model mismatch | Check full model ID, protocol, and request shape |
| 401 | Invalid, expired, disabled key or disallowed IP | Check key status and source IP |
| 402 | Insufficient balance or another credit issue | Inspect the body and available credit |
| 403 | Permission denied or key spending cap reached | Check scope and key cap |
| 429 | Throughput or upstream capacity limit | Honor Retry-After and use bounded backoff |
| 5xx | Gateway or upstream failure | Record request ID and assess retry suitability |
Inspect error type, code, and message together. Do not blindly replay requests that have started output or executed tools. See error handling, rate limits, and troubleshooting.
SDK integration
CanalAPI ships no proprietary SDK — it's a drop-in replacement for the major vendor SDKs. Swap the base URL and your existing code keeps working.
OpenAI Official SDK
Use for /v1/chat/completions, /v1/embeddings, /v1/images/, /v1/audio/, /v1/moderations, /v1/responses. Just set base_url to https://api.canalapi.com/v1.
pip install openai
# JavaScript / TypeScript
npm install openaiAnthropic Official SDK
Use for the native /v1/messages endpoint. Set base_url to https://api.canalapi.com and pass your CanalAPI key via x-api-key.
pip install anthropic
# JavaScript / TypeScript
npm install @anthropic-ai/sdk