このガイドでは、アプリを YouRouter に接続し、テストリクエストを送ってレスポンス形式を確認するまでの流れを説明します。YouRouter は https://api.yourouter.ai/v1 に OpenAI 互換エンドポイントを提供するため、多くの既存 OpenAI SDK 連携では Base URL と API キー を差し替えるだけで移行できます。
連携の前提
| 項目 | 値 |
|---|
| Base URL | https://api.yourouter.ai/v1 |
| 認証ヘッダー | Authorization: Bearer <YOUROUTER_API_KEY> |
| Content-Type | Content-Type: application/json |
| モデル指定 | リクエストボディの model にモデル ID を指定 |
| マルチモーダル | messages[].content にテキストと画像ブロックを並べる |
| デフォルトルーティング | vendor を省略するか vendor: auto |
| プロバイダー固定 | vendor: openai / anthropic / google など |
1. API キーを設定する
以下の例を実行する前に、API キーを環境変数へ保存してください。
export YOUROUTER_API_KEY="your-api-key-here"
set YOUROUTER_API_KEY=your-api-key-here
YOUROUTER_API_KEY=your-api-key-here
API キーをブラウザ拡張、モバイルアプリ、公開リポジトリ、クライアントログに埋め込まないでください。
2. 最初のテストリクエスト
最も早い疎通確認は、Chat Completions への直接 HTTP リクエストです。成功すると choices[0].message.content に生成テキストが入ります。cURL または任意の標準 HTTP クライアントを利用できます。以下の例は Python、Node.js、Go、Java、PHP、Rust を含みます。
cURL
Python requests
Node.js 18+ fetch
Go
Java 11+
PHP
Rust
curl https://api.yourouter.ai/v1/chat/completions \
-H "Authorization: Bearer $YOUROUTER_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-4o",
"messages": [
{
"role": "user",
"content": "Reply with exactly: connected"
}
]
}'
import os
import requests
response = requests.post(
"https://api.yourouter.ai/v1/chat/completions",
headers={
"Authorization": f"Bearer {os.environ['YOUROUTER_API_KEY']}",
"Content-Type": "application/json",
},
json={
"model": "gpt-4o",
"messages": [
{
"role": "user",
"content": "Reply with exactly: connected",
}
],
},
)
response.raise_for_status()
print(response.json()["choices"][0]["message"]["content"])
// quickstart.mjs として保存し、Node.js 18+ で実行します。
const response = await fetch('https://api.yourouter.ai/v1/chat/completions', {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.YOUROUTER_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: 'gpt-4o',
messages: [
{
role: 'user',
content: 'Reply with exactly: connected',
},
],
}),
});
if (!response.ok) {
throw new Error(await response.text());
}
const data = await response.json();
console.log(data.choices[0].message.content);
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
func main() {
payload, _ := json.Marshal(map[string]any{
"model": "gpt-4o",
"messages": []map[string]string{
{"role": "user", "content": "Reply with exactly: connected"},
},
})
req, err := http.NewRequest(
"POST",
"https://api.yourouter.ai/v1/chat/completions",
bytes.NewReader(payload),
)
if err != nil {
panic(err)
}
req.Header.Set("Authorization", "Bearer "+os.Getenv("YOUROUTER_API_KEY"))
req.Header.Set("Content-Type", "application/json")
res, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer res.Body.Close()
if res.StatusCode >= 400 {
body, _ := io.ReadAll(res.Body)
panic(fmt.Sprintf("request failed: %s\n%s", res.Status, body))
}
var result struct {
Choices []struct {
Message struct {
Content string `json:"content"`
} `json:"message"`
} `json:"choices"`
}
if err := json.NewDecoder(res.Body).Decode(&result); err != nil {
panic(err)
}
fmt.Println(result.Choices[0].Message.Content)
}
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class Quickstart {
public static void main(String[] args) throws Exception {
String body = String.join("\n",
"{",
" \"model\": \"gpt-4o\",",
" \"messages\": [",
" {",
" \"role\": \"user\",",
" \"content\": \"Reply with exactly: connected\"",
" }",
" ]",
"}"
);
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.yourouter.ai/v1/chat/completions"))
.header("Authorization", "Bearer " + System.getenv("YOUROUTER_API_KEY"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(body))
.build();
HttpResponse<String> response = HttpClient.newHttpClient().send(
request,
HttpResponse.BodyHandlers.ofString()
);
if (response.statusCode() >= 400) {
throw new RuntimeException(response.body());
}
System.out.println(response.body());
}
}
<?php
$apiKey = getenv('YOUROUTER_API_KEY');
$payload = json_encode([
'model' => 'gpt-4o',
'messages' => [
[
'role' => 'user',
'content' => 'Reply with exactly: connected',
],
],
]);
$ch = curl_init('https://api.yourouter.ai/v1/chat/completions');
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . $apiKey,
'Content-Type: application/json',
],
CURLOPT_POSTFIELDS => $payload,
]);
$response = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($response === false) {
throw new RuntimeException(curl_error($ch));
}
curl_close($ch);
if ($status >= 400) {
throw new RuntimeException($response);
}
$data = json_decode($response, true);
echo $data['choices'][0]['message']['content'] . PHP_EOL;
cargo add reqwest --features blocking,json
cargo add serde_json
use reqwest::blocking::Client;
use serde_json::json;
use std::env;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let api_key = env::var("YOUROUTER_API_KEY")?;
let response: serde_json::Value = Client::new()
.post("https://api.yourouter.ai/v1/chat/completions")
.bearer_auth(api_key)
.json(&json!({
"model": "gpt-4o",
"messages": [
{
"role": "user",
"content": "Reply with exactly: connected"
}
]
}))
.send()?
.error_for_status()?
.json()?;
if let Some(content) = response["choices"][0]["message"]["content"].as_str() {
println!("{content}");
}
Ok(())
}
3. 既存の OpenAI SDK から移行する
アプリがすでに OpenAI SDK を使っている場合、リクエストボディはそのままにして api_key と base_url だけ を差し替えます。
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ["YOUROUTER_API_KEY"],
base_url="https://api.yourouter.ai/v1",
)
completion = client.chat.completions.create(
model="gpt-4o",
messages=[
{
"role": "user",
"content": "Reply with exactly: connected",
}
],
)
print(completion.choices[0].message.content)
import OpenAI from 'openai';
const openai = new OpenAI({
apiKey: process.env.YOUROUTER_API_KEY,
baseURL: 'https://api.yourouter.ai/v1',
});
const completion = await openai.chat.completions.create({
model: 'gpt-4o',
messages: [
{
role: 'user',
content: 'Reply with exactly: connected',
},
],
});
console.log(completion.choices[0].message.content);
Go、Java、PHP、Rust でも同じカスタム Base URL の考え方を使います。利用している OpenAI 互換 SDK が base URL 設定に対応している場合は https://api.yourouter.ai/v1 を指定し、対応していない場合は上記の HTTP 例で /v1/chat/completions を直接呼び出してください。
4. モデルとルーティングを選ぶ
model で呼び出すモデルを指定します。OpenAI GPT、Claude、Gemini、DeepSeek、Grok、Doubao、Kimi など、多くのモデル群を同じ API 形で呼び出せます。画像などマルチモーダル入力は マルチモーダル を参照してください。
デフォルトでは YouRouter が自動ルーティングします。vendor を省略するか vendor: auto にすると、モデルに対して最も適切な上流へ振り分けます。
特定の上流の挙動、モデル亜種、アカウント分離、コンプライアンス要件などが明確な場合のみ、vendor で固定してください。
cURL
Python SDK
Node.js SDK
curl https://api.yourouter.ai/v1/chat/completions \
-H "Authorization: Bearer $YOUROUTER_API_KEY" \
-H "Content-Type: application/json" \
-H "vendor: openai" \
-d '{
"model": "gpt-4o",
"messages": [{"role": "user", "content": "Hello from a pinned provider."}]
}'
completion = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Hello from a pinned provider."}],
extra_headers={"vendor": "openai"},
)
const completion = await openai.chat.completions.create({
model: 'gpt-4o',
messages: [{ role: 'user', content: 'Hello from a pinned provider.' }],
}, {
headers: { vendor: 'openai' },
});
モデル API の例は モデル を参照してください。プロバイダー ID、自動フェイルオーバーの挙動、本番運用の推奨事項は ルーティング にまとめています。
5. レスポンスとエラー処理
OpenAI 互換エンドポイントでは、成功レスポンスは OpenAI 形式に従います。生成テキストは通常 choices[0].message.content です。
{
"choices": [
{
"message": {
"role": "assistant",
"content": "connected"
}
}
]
}
よくある HTTP ステータス:
| ステータス | 意味 | 対応 |
|---|
200 | 成功 | ボディをパースする |
401 | API キー不正/未設定 | Authorization を確認 |
429 | レート制限 | バックオフして再試行、ルーティング見直し |
500 | ゲートウェイ/上流エラー | 安全に再試行し、リクエスト ID を残す |
6. ストリーミング
チャット UI やエージェント用途では stream: true で逐次チャンクを受け取れます。
stream = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Explain automatic routing in two sentences."}],
stream=True,
)
for chunk in stream:
delta = chunk.choices[0].delta.content
if delta:
print(delta, end="")
詳細なリクエスト形は Create Chat Completion を参照してください。
次のステップ
API リファレンス
エンドポイント、パラメータ、レスポンス形式を確認します。
モデル
モデル ID の渡し方と API 経由でのモデル切り替えを確認します。
マルチモーダル
画像入力を送り、プロバイダー固有のマルチモーダル API を呼び出します。
ルーティング
自動ルーティングとプロバイダー固定を使い分ける場面を確認します。
Chat Completions
会話、ストリーミング UI、ツール、マルチモーダルフローを構築します。