客户端 SDK
使用 OpenAI SDK、Anthropic SDK 或任意 HTTP 客户端接入 ClawdRouter。
推荐优先使用 OpenAI-compatible 接口完成文本、流式输出、图片等常规调用;
只有在需要 Anthropic 原生 Messages 协议时,再使用 Anthropic SDK 或 /v1/messages。
选择接入方式
- Base URL
DOCS_API_ORIGIN/v1- 主要接口
/v1/chat/completions/v1/responses/v1/images/generations
- Base URL
DOCS_API_ORIGIN- 主要接口
/v1/messages
- Base URL
- 按接口选择
- 主要接口
- 所有 API endpoint
准备 API Key
所有示例都使用同一个 API Key。建议通过环境变量管理密钥:
export CLAWDROUTER_API_KEY="YOUR_API_KEY"
export CLAWDROUTER_BASE_URL="__DOCS_API_ORIGIN__"
如果项目直接使用 OpenAI SDK 的默认环境变量,也可以这样配置:
export OPENAI_API_KEY="YOUR_API_KEY"
export OPENAI_BASE_URL="__DOCS_API_ORIGIN__/v1"
Anthropic SDK 使用同一个 API Key,但 base_url 应设置为 __DOCS_API_ORIGIN__,不要带 /v1。
安装 SDK
- cURL
- Python
- Node.js
- Go
- Java
- PHP
- Ruby
- C#
cURL 通常已经内置在 macOS 和 Linux 中。Windows 用户可以使用 PowerShell、Git Bash 或 WSL。
pip install openai
npm install openai
Go 示例使用标准库 net/http,不需要额外安装依赖。
Java 示例使用 JDK 11+ 内置的 java.net.http.HttpClient,不需要额外安装依赖。
PHP 示例使用内置 cURL 扩展。请确认运行环境已启用 curl。
Ruby 示例使用标准库 net/http,不需要额外安装依赖。
C# 示例使用 .NET 内置 HttpClient,不需要额外安装依赖。
发起文本生成请求
以下示例使用 OpenAI-compatible Chat Completions 接口。适合大多数聊天、问答和文本生成场景。
POST __DOCS_API_ORIGIN__/v1/chat/completions
- cURL
- Python
- Node.js
- Go
- Java
- PHP
- Ruby
- C#
curl __DOCS_API_ORIGIN__/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $CLAWDROUTER_API_KEY" \
-d '{
"model": "gpt-4o",
"messages": [
{"role": "system", "content": "你是一个有用的助手"},
{"role": "user", "content": "用简单的话解释什么是机器学习"}
]
}'
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ["CLAWDROUTER_API_KEY"],
base_url="__DOCS_API_ORIGIN__/v1",
)
completion = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "你是一个有用的助手"},
{"role": "user", "content": "用简单的话解释什么是机器学习"},
],
)
print(completion.choices[0].message.content)
import OpenAI from "openai";
const client = new OpenAI({
apiKey: process.env.CLAWDROUTER_API_KEY,
baseURL: "__DOCS_API_ORIGIN__/v1",
});
const completion = await client.chat.completions.create({
model: "gpt-4o",
messages: [
{ role: "system", content: "你是一个有用的助手" },
{ role: "user", content: "用简单的话解释什么是机器学习" },
],
});
console.log(completion.choices[0].message.content);
package main
import (
"bytes"
"fmt"
"io"
"net/http"
"os"
)
func main() {
body := []byte(`{
"model": "gpt-4o",
"messages": [
{"role": "system", "content": "你是一个有用的助手"},
{"role": "user", "content": "用简单的话解释什么是机器学习"}
]
}`)
req, _ := http.NewRequest(
"POST",
"__DOCS_API_ORIGIN__/v1/chat/completions",
bytes.NewReader(body),
)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+os.Getenv("CLAWDROUTER_API_KEY"))
resp, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
data, _ := io.ReadAll(resp.Body)
fmt.Println(string(data))
}
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class Main {
public static void main(String[] args) throws Exception {
String body = """
{
"model": "gpt-4o",
"messages": [
{"role": "system", "content": "你是一个有用的助手"},
{"role": "user", "content": "用简单的话解释什么是机器学习"}
]
}
""";
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("__DOCS_API_ORIGIN__/v1/chat/completions"))
.header("Content-Type", "application/json")
.header("Authorization", "Bearer " + System.getenv("CLAWDROUTER_API_KEY"))
.POST(HttpRequest.BodyPublishers.ofString(body))
.build();
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
}
}
<?php
$payload = [
"model" => "gpt-4o",
"messages" => [
["role" => "system", "content" => "你是一个有用的助手"],
["role" => "user", "content" => "用简单的话解释什么是机器学习"],
],
];
$ch = curl_init("__DOCS_API_ORIGIN__/v1/chat/completions");
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => [
"Content-Type: application/json",
"Authorization: Bearer " . getenv("CLAWDROUTER_API_KEY"),
],
CURLOPT_POSTFIELDS => json_encode($payload, JSON_UNESCAPED_UNICODE),
]);
$response = curl_exec($ch);
curl_close($ch);
echo $response . PHP_EOL;
require "json"
require "net/http"
require "uri"
uri = URI("__DOCS_API_ORIGIN__/v1/chat/completions")
request = Net::HTTP::Post.new(uri)
request["Content-Type"] = "application/json"
request["Authorization"] = "Bearer #{ENV.fetch('CLAWDROUTER_API_KEY')}"
request.body = {
model: "gpt-4o",
messages: [
{ role: "system", content: "你是一个有用的助手" },
{ role: "user", content: "用简单的话解释什么是机器学习" },
],
}.to_json
response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
http.request(request)
end
puts response.body
using System.Net.Http.Headers;
using System.Text;
using var client = new HttpClient();
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("CLAWDROUTER_API_KEY"));
var json = """
{
"model": "gpt-4o",
"messages": [
{"role": "system", "content": "你是一个有用的助手"},
{"role": "user", "content": "用简单的话解释什么是机器学习"}
]
}
""";
var response = await client.PostAsync(
"__DOCS_API_ORIGIN__/v1/chat/completions",
new StringContent(json, Encoding.UTF8, "application/json")
);
Console.WriteLine(await response.Content.ReadAsStringAsync());
成功后,非流式响应会返回 choices[].message.content;如果需要完整字段说明,请查看 Chat Completions API 参考。
流式输出
流式输出适合聊天界面、长文本生成和需要更快首字响应的场景。请求体中设置 stream: true 即可。
- cURL
- Python
- Node.js
- Go
- Java
- PHP
- Ruby
- C#
curl __DOCS_API_ORIGIN__/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $CLAWDROUTER_API_KEY" \
-N \
-d '{
"model": "gpt-4o",
"messages": [
{"role": "user", "content": "写一篇关于人工智能的短文"}
],
"stream": true
}'
-N 会关闭 cURL 输出缓冲,让内容实时显示。
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ["CLAWDROUTER_API_KEY"],
base_url="__DOCS_API_ORIGIN__/v1",
)
stream = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "user", "content": "写一篇关于人工智能的短文"},
],
stream=True,
)
for chunk in stream:
content = chunk.choices[0].delta.content
if content:
print(content, end="", flush=True)
import OpenAI from "openai";
const client = new OpenAI({
apiKey: process.env.CLAWDROUTER_API_KEY,
baseURL: "__DOCS_API_ORIGIN__/v1",
});
const stream = await client.chat.completions.create({
model: "gpt-4o",
messages: [{ role: "user", content: "写一篇关于人工智能的短文" }],
stream: true,
});
for await (const chunk of stream) {
const content = chunk.choices[0]?.delta?.content;
if (content) {
process.stdout.write(content);
}
}
package main
import (
"bufio"
"bytes"
"fmt"
"net/http"
"os"
)
func main() {
body := []byte(`{
"model": "gpt-4o",
"messages": [
{"role": "user", "content": "写一篇关于人工智能的短文"}
],
"stream": true
}`)
req, _ := http.NewRequest(
"POST",
"__DOCS_API_ORIGIN__/v1/chat/completions",
bytes.NewReader(body),
)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+os.Getenv("CLAWDROUTER_API_KEY"))
resp, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
scanner := bufio.NewScanner(resp.Body)
for scanner.Scan() {
fmt.Println(scanner.Text())
}
}
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class Main {
public static void main(String[] args) throws Exception {
String body = """
{
"model": "gpt-4o",
"messages": [
{"role": "user", "content": "写一篇关于人工智能的短文"}
],
"stream": true
}
""";
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("__DOCS_API_ORIGIN__/v1/chat/completions"))
.header("Content-Type", "application/json")
.header("Authorization", "Bearer " + System.getenv("CLAWDROUTER_API_KEY"))
.POST(HttpRequest.BodyPublishers.ofString(body))
.build();
HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofLines())
.body()
.forEach(System.out::println);
}
}
<?php
$payload = [
"model" => "gpt-4o",
"messages" => [
["role" => "user", "content" => "写一篇关于人工智能的短文"],
],
"stream" => true,
];
$ch = curl_init("__DOCS_API_ORIGIN__/v1/chat/completions");
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => [
"Content-Type: application/json",
"Authorization: Bearer " . getenv("CLAWDROUTER_API_KEY"),
],
CURLOPT_POSTFIELDS => json_encode($payload, JSON_UNESCAPED_UNICODE),
CURLOPT_WRITEFUNCTION => function ($ch, $chunk) {
echo $chunk;
flush();
return strlen($chunk);
},
]);
curl_exec($ch);
curl_close($ch);
require "json"
require "net/http"
require "uri"
uri = URI("__DOCS_API_ORIGIN__/v1/chat/completions")
request = Net::HTTP::Post.new(uri)
request["Content-Type"] = "application/json"
request["Authorization"] = "Bearer #{ENV.fetch('CLAWDROUTER_API_KEY')}"
request.body = {
model: "gpt-4o",
messages: [
{ role: "user", content: "写一篇关于人工智能的短文" },
],
stream: true,
}.to_json
Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
http.request(request) do |response|
response.read_body do |chunk|
print chunk
end
end
end
using System.Net.Http.Headers;
using System.Text;
using var client = new HttpClient();
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("CLAWDROUTER_API_KEY"));
var json = """
{
"model": "gpt-4o",
"messages": [
{"role": "user", "content": "写一篇关于人工智能的短文"}
],
"stream": true
}
""";
using var request = new HttpRequestMessage(HttpMethod.Post, "__DOCS_API_ORIGIN__/v1/chat/completions") {
Content = new StringContent(json, Encoding.UTF8, "application/json")
};
using var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
await using var stream = await response.Content.ReadAsStreamAsync();
using var reader = new StreamReader(stream);
while (!reader.EndOfStream) {
Console.WriteLine(await reader.ReadLineAsync());
}
调用 Veo 视频生成
视频生成是异步任务。提交成功后会返回 task_id,请到控制台任务中心下载生成结果。
- cURL
- Python
- Node.js
- Go
- Java
- PHP
- Ruby
- C#
curl __DOCS_API_ORIGIN__/v1/video/generations \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $CLAWDROUTER_API_KEY" \
-d '{
"model": "veo-3.1-fast-generate-001",
"prompt": "A cute small bird dancing on a tree branch, moving rhythmically to cheerful music. The bird gently sways its body, lightly flaps its wings, and playfully tilts its head. Bright forest background with soft sunlight and subtle shadows. Semi-realistic, slightly cartoon style, vivid but not over-saturated colors. Static camera, centered subject, smooth motion, medium detail. 720p resolution, clear and stable output.",
"duration": 4,
"metadata": {
"durationSeconds": 4,
"aspectRatio": "16:9",
"resolution": "720p",
"negativePrompt": "low quality, blurry, distorted",
"personGeneration": "allow_adult",
"generateAudio": true
}
}'
import os
import requests
response = requests.post(
"__DOCS_API_ORIGIN__/v1/video/generations",
headers={
"Authorization": f"Bearer {os.environ['CLAWDROUTER_API_KEY']}",
"Content-Type": "application/json",
},
json={
"model": "veo-3.1-fast-generate-001",
"prompt": "A cute small bird dancing on a tree branch, moving rhythmically to cheerful music. The bird gently sways its body, lightly flaps its wings, and playfully tilts its head. Bright forest background with soft sunlight and subtle shadows. Semi-realistic, slightly cartoon style, vivid but not over-saturated colors. Static camera, centered subject, smooth motion, medium detail. 720p resolution, clear and stable output.",
"duration": 4,
"metadata": {
"durationSeconds": 4,
"aspectRatio": "16:9",
"resolution": "720p",
"negativePrompt": "low quality, blurry, distorted",
"personGeneration": "allow_adult",
"generateAudio": True,
},
},
)
print(response.json())
const response = await fetch("__DOCS_API_ORIGIN__/v1/video/generations", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.CLAWDROUTER_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "veo-3.1-fast-generate-001",
prompt:
"A cute small bird dancing on a tree branch, moving rhythmically to cheerful music. The bird gently sways its body, lightly flaps its wings, and playfully tilts its head. Bright forest background with soft sunlight and subtle shadows. Semi-realistic, slightly cartoon style, vivid but not over-saturated colors. Static camera, centered subject, smooth motion, medium detail. 720p resolution, clear and stable output.",
duration: 4,
metadata: {
durationSeconds: 4,
aspectRatio: "16:9",
resolution: "720p",
negativePrompt: "low quality, blurry, distorted",
personGeneration: "allow_adult",
generateAudio: true,
},
}),
});
console.log(await response.json());
package main
import (
"bytes"
"fmt"
"io"
"net/http"
"os"
)
func main() {
body := []byte(`{
"model": "veo-3.1-fast-generate-001",
"prompt": "A cute small bird dancing on a tree branch, moving rhythmically to cheerful music. The bird gently sways its body, lightly flaps its wings, and playfully tilts its head. Bright forest background with soft sunlight and subtle shadows. Semi-realistic, slightly cartoon style, vivid but not over-saturated colors. Static camera, centered subject, smooth motion, medium detail. 720p resolution, clear and stable output.",
"duration": 4,
"metadata": {
"durationSeconds": 4,
"aspectRatio": "16:9",
"resolution": "720p",
"negativePrompt": "low quality, blurry, distorted",
"personGeneration": "allow_adult",
"generateAudio": true
}
}`)
req, _ := http.NewRequest(
"POST",
"__DOCS_API_ORIGIN__/v1/video/generations",
bytes.NewReader(body),
)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+os.Getenv("CLAWDROUTER_API_KEY"))
resp, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
data, _ := io.ReadAll(resp.Body)
fmt.Println(string(data))
}
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class Main {
public static void main(String[] args) throws Exception {
String body = """
{
"model": "veo-3.1-fast-generate-001",
"prompt": "A cute small bird dancing on a tree branch, moving rhythmically to cheerful music. The bird gently sways its body, lightly flaps its wings, and playfully tilts its head. Bright forest background with soft sunlight and subtle shadows. Semi-realistic, slightly cartoon style, vivid but not over-saturated colors. Static camera, centered subject, smooth motion, medium detail. 720p resolution, clear and stable output.",
"duration": 4,
"metadata": {
"durationSeconds": 4,
"aspectRatio": "16:9",
"resolution": "720p",
"negativePrompt": "low quality, blurry, distorted",
"personGeneration": "allow_adult",
"generateAudio": true
}
}
""";
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("__DOCS_API_ORIGIN__/v1/video/generations"))
.header("Content-Type", "application/json")
.header("Authorization", "Bearer " + System.getenv("CLAWDROUTER_API_KEY"))
.POST(HttpRequest.BodyPublishers.ofString(body))
.build();
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
}
}
<?php
$payload = [
"model" => "veo-3.1-fast-generate-001",
"prompt" => "A cute small bird dancing on a tree branch, moving rhythmically to cheerful music. The bird gently sways its body, lightly flaps its wings, and playfully tilts its head. Bright forest background with soft sunlight and subtle shadows. Semi-realistic, slightly cartoon style, vivid but not over-saturated colors. Static camera, centered subject, smooth motion, medium detail. 720p resolution, clear and stable output.",
"duration" => 4,
"metadata" => [
"durationSeconds" => 4,
"aspectRatio" => "16:9",
"resolution" => "720p",
"negativePrompt" => "low quality, blurry, distorted",
"personGeneration" => "allow_adult",
"generateAudio" => true,
],
];
$ch = curl_init("__DOCS_API_ORIGIN__/v1/video/generations");
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => [
"Content-Type: application/json",
"Authorization: Bearer " . getenv("CLAWDROUTER_API_KEY"),
],
CURLOPT_POSTFIELDS => json_encode($payload, JSON_UNESCAPED_UNICODE),
]);
$response = curl_exec($ch);
curl_close($ch);
echo $response . PHP_EOL;
require "json"
require "net/http"
require "uri"
uri = URI("__DOCS_API_ORIGIN__/v1/video/generations")
request = Net::HTTP::Post.new(uri)
request["Content-Type"] = "application/json"
request["Authorization"] = "Bearer #{ENV.fetch('CLAWDROUTER_API_KEY')}"
request.body = {
model: "veo-3.1-fast-generate-001",
prompt: "A cute small bird dancing on a tree branch, moving rhythmically to cheerful music. The bird gently sways its body, lightly flaps its wings, and playfully tilts its head. Bright forest background with soft sunlight and subtle shadows. Semi-realistic, slightly cartoon style, vivid but not over-saturated colors. Static camera, centered subject, smooth motion, medium detail. 720p resolution, clear and stable output.",
duration: 4,
metadata: {
durationSeconds: 4,
aspectRatio: "16:9",
resolution: "720p",
negativePrompt: "low quality, blurry, distorted",
personGeneration: "allow_adult",
generateAudio: true,
},
}.to_json
response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
http.request(request)
end
puts response.body
using System.Net.Http.Headers;
using System.Text;
using var client = new HttpClient();
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("CLAWDROUTER_API_KEY"));
var json = """
{
"model": "veo-3.1-fast-generate-001",
"prompt": "A cute small bird dancing on a tree branch, moving rhythmically to cheerful music. The bird gently sways its body, lightly flaps its wings, and playfully tilts its head. Bright forest background with soft sunlight and subtle shadows. Semi-realistic, slightly cartoon style, vivid but not over-saturated colors. Static camera, centered subject, smooth motion, medium detail. 720p resolution, clear and stable output.",
"duration": 4,
"metadata": {
"durationSeconds": 4,
"aspectRatio": "16:9",
"resolution": "720p",
"negativePrompt": "low quality, blurry, distorted",
"personGeneration": "allow_adult",
"generateAudio": true
}
}
""";
var response = await client.PostAsync(
"__DOCS_API_ORIGIN__/v1/video/generations",
new StringContent(json, Encoding.UTF8, "application/json")
);
Console.WriteLine(await response.Content.ReadAsStringAsync());
典型受理响应:
{
"id": "task_MrvezeP3uOim5bWo8texognLwHHHVgpB",
"task_id": "task_MrvezeP3uOim5bWo8texognLwHHHVgpB",
"object": "video",
"model": "veo-3.1-fast-generate-001",
"status": "queued",
"progress": 0,
"created_at": 1779265222
}
调用 Anthropic 原生协议
如果你需要直接使用 Anthropic Messages 协议,请调用 /v1/messages。该协议使用 x-api-key 认证头,而不是 Authorization: Bearer。
- cURL
- Python
- Node.js
- Go
- Java
- PHP
- Ruby
- C#
curl __DOCS_API_ORIGIN__/v1/messages \
-H "Content-Type: application/json" \
-H "x-api-key: $CLAWDROUTER_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-d '{
"model": "claude-sonnet-4-6",
"max_tokens": 1024,
"messages": [
{"role": "user", "content": "用简单的话解释什么是机器学习"}
]
}'
import os
import anthropic
client = anthropic.Anthropic(
api_key=os.environ["CLAWDROUTER_API_KEY"],
base_url="__DOCS_API_ORIGIN__",
)
message = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=1024,
messages=[
{"role": "user", "content": "用简单的话解释什么是机器学习"},
],
)
print(message.content[0].text)
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic({
apiKey: process.env.CLAWDROUTER_API_KEY,
baseURL: "__DOCS_API_ORIGIN__",
});
const message = await client.messages.create({
model: "claude-sonnet-4-6",
max_tokens: 1024,
messages: [
{ role: "user", content: "用简单的话解释什么是机器学习" },
],
});
console.log(message.content[0].text);
package main
import (
"bytes"
"fmt"
"io"
"net/http"
"os"
)
func main() {
body := []byte(`{
"model": "claude-sonnet-4-6",
"max_tokens": 1024,
"messages": [
{"role": "user", "content": "用简单的话解释什么是机器学习"}
]
}`)
req, _ := http.NewRequest(
"POST",
"__DOCS_API_ORIGIN__/v1/messages",
bytes.NewReader(body),
)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("x-api-key", os.Getenv("CLAWDROUTER_API_KEY"))
req.Header.Set("anthropic-version", "2023-06-01")
resp, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
data, _ := io.ReadAll(resp.Body)
fmt.Println(string(data))
}
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class Main {
public static void main(String[] args) throws Exception {
String body = """
{
"model": "claude-sonnet-4-6",
"max_tokens": 1024,
"messages": [
{"role": "user", "content": "用简单的话解释什么是机器学习"}
]
}
""";
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("__DOCS_API_ORIGIN__/v1/messages"))
.header("Content-Type", "application/json")
.header("x-api-key", System.getenv("CLAWDROUTER_API_KEY"))
.header("anthropic-version", "2023-06-01")
.POST(HttpRequest.BodyPublishers.ofString(body))
.build();
HttpResponse<String> response = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
}
}
<?php
$payload = [
"model" => "claude-sonnet-4-6",
"max_tokens" => 1024,
"messages" => [
["role" => "user", "content" => "用简单的话解释什么是机器学习"],
],
];
$ch = curl_init("__DOCS_API_ORIGIN__/v1/messages");
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => [
"Content-Type: application/json",
"x-api-key: " . getenv("CLAWDROUTER_API_KEY"),
"anthropic-version: 2023-06-01",
],
CURLOPT_POSTFIELDS => json_encode($payload, JSON_UNESCAPED_UNICODE),
]);
$response = curl_exec($ch);
curl_close($ch);
echo $response . PHP_EOL;
require "json"
require "net/http"
require "uri"
uri = URI("__DOCS_API_ORIGIN__/v1/messages")
request = Net::HTTP::Post.new(uri)
request["Content-Type"] = "application/json"
request["x-api-key"] = ENV.fetch("CLAWDROUTER_API_KEY")
request["anthropic-version"] = "2023-06-01"
request.body = {
model: "claude-sonnet-4-6",
max_tokens: 1024,
messages: [
{ role: "user", content: "用简单的话解释什么是机器学习" },
],
}.to_json
response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
http.request(request)
end
puts response.body
using System.Text;
using var client = new HttpClient();
client.DefaultRequestHeaders.Add("x-api-key", Environment.GetEnvironmentVariable("CLAWDROUTER_API_KEY"));
client.DefaultRequestHeaders.Add("anthropic-version", "2023-06-01");
var json = """
{
"model": "claude-sonnet-4-6",
"max_tokens": 1024,
"messages": [
{"role": "user", "content": "用简单的话解释什么是机器学习"}
]
}
""";
var response = await client.PostAsync(
"__DOCS_API_ORIGIN__/v1/messages",
new StringContent(json, Encoding.UTF8, "application/json")
);
Console.WriteLine(await response.Content.ReadAsStringAsync());
常见配置
| 配置 | 推荐值 | 说明 |
|---|---|---|
| OpenAI-compatible Base URL | __DOCS_API_ORIGIN__/v1 | OpenAI SDK、Chat Completions、Responses、Images API 使用 |
| Anthropic Base URL | __DOCS_API_ORIGIN__ | Anthropic SDK 和 Messages API 使用 |
| 认证头 | Authorization: Bearer YOUR_API_KEY | OpenAI-compatible 接口使用 |
| Anthropic 认证头 | x-api-key: YOUR_API_KEY | Anthropic 原生协议使用 |
| Content-Type | application/json | 所有 JSON 请求都需要 |
| Request-Id | 自定义唯一字符串 | 可选,用于业务侧幂等和排查 |
错误处理建议
401通常表示 API Key 无效、缺失或被禁用。429通常表示请求频率或额度达到限制,可以稍后重试或调整并发。5xx通常表示平台或上游模型服务异常,建议保留request_id后重试或提交工单。- 视频生成返回
queued只代表任务已受理,不代表视频已经完成。
下一步
- 快速开始 - 查看完整接入流程
- 认证鉴权 - 了解 API Key 和请求头
- OpenAI 聊天补全 - 查看完整参数说明
- Veo 视频生成 - 查看视频生成字段和使用技巧