> ## Documentation Index
> Fetch the complete documentation index at: https://docs.yourouter.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# API クイックスタート

> 数分で YouRouter API に接続し、最初のリクエストを成功させます。

このガイドでは、アプリを YouRouter に接続し、テストリクエストを送ってレスポンス形式を確認するまでの流れを説明します。YouRouter は `https://api.yourouter.ai/v1` に OpenAI 互換エンドポイントを提供するため、多くの既存 OpenAI SDK 連携では **Base URL と API キー** を差し替えるだけで移行できます。

<Note>
  API キーが必要ですか？[YouRouter Dashboard](https://platform.yourouter.ai/dashboard) で作成できます。
</Note>

## 連携の前提

| 項目           | 値                                            |
| ------------ | -------------------------------------------- |
| 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 キーを環境変数へ保存してください。

<Tabs>
  <Tab title="macOS/Linux">
    ```bash theme={null}
    export YOUROUTER_API_KEY="your-api-key-here"
    ```
  </Tab>

  <Tab title="Windows">
    ```cmd theme={null}
    set YOUROUTER_API_KEY=your-api-key-here
    ```
  </Tab>

  <Tab title=".env">
    ```bash theme={null}
    YOUROUTER_API_KEY=your-api-key-here
    ```
  </Tab>
</Tabs>

<Warning>
  API キーをブラウザ拡張、モバイルアプリ、公開リポジトリ、クライアントログに埋め込まないでください。
</Warning>

## 2. 最初のテストリクエスト

最も早い疎通確認は、Chat Completions への直接 HTTP リクエストです。成功すると `choices[0].message.content` に生成テキストが入ります。cURL または任意の標準 HTTP クライアントを利用できます。以下の例は Python、Node.js、Go、Java、PHP、Rust を含みます。

<Tabs>
  <Tab title="cURL">
    ```bash theme={null}
    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"
          }
        ]
      }'
    ```
  </Tab>

  <Tab title="Python requests">
    ```bash theme={null}
    pip install requests
    ```

    ```python theme={null}
    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"])
    ```
  </Tab>

  <Tab title="Node.js 18+ fetch">
    ```javascript theme={null}
    // 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);
    ```
  </Tab>

  <Tab title="Go">
    ```go theme={null}
    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)
    }
    ```
  </Tab>

  <Tab title="Java 11+">
    ```java theme={null}
    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());
        }
    }
    ```
  </Tab>

  <Tab title="PHP">
    ```php theme={null}
    <?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;
    ```
  </Tab>

  <Tab title="Rust">
    ```bash theme={null}
    cargo add reqwest --features blocking,json
    cargo add serde_json
    ```

    ```rust theme={null}
    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(())
    }
    ```
  </Tab>
</Tabs>

## 3. 既存の OpenAI SDK から移行する

アプリがすでに OpenAI SDK を使っている場合、リクエストボディはそのままにして **`api_key` と `base_url` だけ** を差し替えます。

<Tabs>
  <Tab title="Python">
    ```bash theme={null}
    pip install openai
    ```

    ```python theme={null}
    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)
    ```
  </Tab>

  <Tab title="Node.js">
    ```bash theme={null}
    npm install openai
    ```

    ```javascript theme={null}
    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);
    ```
  </Tab>
</Tabs>

<Note>
  Go、Java、PHP、Rust でも同じカスタム Base URL の考え方を使います。利用している OpenAI 互換 SDK が base URL 設定に対応している場合は `https://api.yourouter.ai/v1` を指定し、対応していない場合は上記の HTTP 例で `/v1/chat/completions` を直接呼び出してください。
</Note>

## 4. モデルとルーティングを選ぶ

`model` で呼び出すモデルを指定します。OpenAI GPT、Claude、Gemini、DeepSeek、Grok、Doubao、Kimi など、多くのモデル群を同じ API 形で呼び出せます。画像などマルチモーダル入力は [マルチモーダル](/ja/guides/multimodal) を参照してください。

<Note>
  サンプルのモデルがアカウントで有効になっていない場合は、[YouRouter Dashboard](https://platform.yourouter.ai/dashboard) に表示される利用可能なモデル ID に置き換えてください。
</Note>

デフォルトでは YouRouter が自動ルーティングします。`vendor` を省略するか `vendor: auto` にすると、モデルに対して最も適切な上流へ振り分けます。

特定の上流の挙動、モデル亜種、アカウント分離、コンプライアンス要件などが明確な場合のみ、`vendor` で固定してください。

<Tabs>
  <Tab title="cURL">
    ```bash theme={null}
    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."}]
      }'
    ```
  </Tab>

  <Tab title="Python SDK">
    ```python theme={null}
    completion = client.chat.completions.create(
        model="gpt-4o",
        messages=[{"role": "user", "content": "Hello from a pinned provider."}],
        extra_headers={"vendor": "openai"},
    )
    ```
  </Tab>

  <Tab title="Node.js SDK">
    ```javascript theme={null}
    const completion = await openai.chat.completions.create({
      model: 'gpt-4o',
      messages: [{ role: 'user', content: 'Hello from a pinned provider.' }],
    }, {
      headers: { vendor: 'openai' },
    });
    ```
  </Tab>
</Tabs>

モデル API の例は [モデル](/ja/model) を参照してください。プロバイダー ID、自動フェイルオーバーの挙動、本番運用の推奨事項は [ルーティング](/ja/guides/router) にまとめています。

## 5. レスポンスとエラー処理

OpenAI 互換エンドポイントでは、成功レスポンスは OpenAI 形式に従います。生成テキストは通常 `choices[0].message.content` です。

```json theme={null}
{
  "choices": [
    {
      "message": {
        "role": "assistant",
        "content": "connected"
      }
    }
  ]
}
```

よくある HTTP ステータス:

| ステータス | 意味           | 対応                   |
| ----- | ------------ | -------------------- |
| `200` | 成功           | ボディをパースする            |
| `401` | API キー不正/未設定 | `Authorization` を確認  |
| `429` | レート制限        | バックオフして再試行、ルーティング見直し |
| `500` | ゲートウェイ/上流エラー | 安全に再試行し、リクエスト ID を残す |

## 6. ストリーミング

チャット UI やエージェント用途では `stream: true` で逐次チャンクを受け取れます。

```python theme={null}
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](/ja/api-reference/chat/create#streaming) を参照してください。

## 次のステップ

<CardGroup cols={2}>
  <Card title="API リファレンス" icon="code" href="/ja/api-reference/introduction">
    エンドポイント、パラメータ、レスポンス形式を確認します。
  </Card>

  <Card title="モデル" icon="sparkles" href="/ja/model">
    モデル ID の渡し方と API 経由でのモデル切り替えを確認します。
  </Card>

  <Card title="マルチモーダル" icon="image" href="/ja/guides/multimodal">
    画像入力を送り、プロバイダー固有のマルチモーダル API を呼び出します。
  </Card>

  <Card title="ルーティング" icon="route" href="/ja/guides/router">
    自動ルーティングとプロバイダー固定を使い分ける場面を確認します。
  </Card>

  <Card title="Chat Completions" icon="message" href="/ja/guides/chat-completions">
    会話、ストリーミング UI、ツール、マルチモーダルフローを構築します。
  </Card>
</CardGroup>
