# API を呼び出す

Authorization Code 認証でトークンを取得し、SSE 経由でエージェントと会話するまでの手順を解説します。

## はじめに

SaaS版の API を利用するための最短ステップを紹介します。以下の4つのステップでエージェントとの会話を開始できます。

> **対象範囲**
>
> このクイックスタートは **Web アプリケーション**（サーバー側で `Client Secret` を保持できる Confidential Client）向けの手順です。SPA / モバイルアプリ（Public Client）の場合は PKCE フローが必須となるため、本クイックスタートはそのままでは利用できません。詳細は[認証ガイド](https://developers.fd.agenticstar.tm.softbank.jp/docs/saas/api/agent/guide/auth-guide.md)を参照してください。
>
> このページの手順（チャット）は、システム連携（サーバー間。Client Credentials フロー）のトークンでは使えません。システム連携のトークンの取り方は[認証ガイド — Client Credentials フロー](https://developers.fd.agenticstar.tm.softbank.jp/docs/saas/api/agent/guide/auth-guide.md#client-credentials-%E3%83%95%E3%83%AD%E3%83%BC)を、プロジェクトを外部システムから操作する場合は、アプリケーションなら[ユーザー API リファレンス — プロジェクト](https://developers.fd.agenticstar.tm.softbank.jp/docs/saas/api/agent/reference/api-reference.md#projects)、システム連携なら[システム連携 API リファレンス — プロジェクト](https://developers.fd.agenticstar.tm.softbank.jp/docs/saas/api/agent/reference/admin-api-reference.md#projects)を参照してください。

> **前提条件**
>
> - API オプションの申込が完了していること
>
> - Console にログインできること（developer ロール以上）
>
> - Console で **Web アプリケーション** タイプのクライアントを作成済みであること（[Consoleガイド](https://developers.fd.agenticstar.tm.softbank.jp/docs/saas/api/agent/guide/console-guide.md)）
>
> - 以下の情報を取得済みであること:
>
>   <!-- -->
>
>   - `Client ID` - 作成したアプリケーションの ID
>   - `Client Secret` - アプリケーションのシークレット
>   - `Redirect URI` - Console に登録済みのリダイレクト先 URL

## Step 1: 認証情報の確認

Console のアプリ詳細画面で、以下の情報を確認してください。

### 例

```text
Client ID: your-app-001
Client Secret: (hidden)
Redirect URI: http://localhost:3000/callback
```

## Step 2: 認可コードの取得

ブラウザで認可エンドポイントにアクセスし、ログイン後に認可コードを取得します。

### 認可 URL の構築

以下の URL をブラウザで開いてください。`client_id`、`redirect_uri`、`state` を自分の値に置き換えてください。

```text
https://auth.fd.agenticstar.tm.softbank.jp/federation/auth/v1/authorize?response_type=code&client_id=<your-client-id>&redirect_uri=<your-redirect-uri>&state=<random-state-value>
```

### パラメータ

- `response_type`: `code` 固定
- `client_id`: Step 1 で確認した Client ID
- `redirect_uri`: Console に登録済みの Redirect URI（URL エンコード済み）
- `state`: CSRF 対策用のランダム文字列（強く推奨）

### ログインと認可

1. ブラウザにログイン画面が表示されます。普段と同じアカウントでログインしてください。
2. 同意画面が有効になっているアプリケーションの場合、初回利用時やスコープ追加時に同意画面が表示されます。内容を確認し、許可してください。

### 認可コードの受け取り

認可が完了すると、ブラウザが `redirect_uri` にリダイレクトされます。URL に含まれる `code` パラメータが認可コードです。

```text
http://localhost:3000/callback?code=AUTH_CODE_VALUE&state=<random-state-value>
```

> **警告**
>
> - `state` を指定した場合は、レスポンスの値がリクエスト時と一致することを必ず検証してください（CSRF 対策）
> - 認可コードの有効期限は短いため、すぐに次のステップでトークンに交換してください

## Step 3: トークンの取得

認可コードをアクセストークンに交換します。サーバー側で以下のリクエストを実行してください。

### リクエスト例

**Exchange authorization code for token**

**curl**

```curl
curl -X POST https://auth.fd.agenticstar.tm.softbank.jp/federation/auth/v1/token \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "grant_type=authorization_code" \
-d "code=<auth-code>" \
-d "redirect_uri=<your-redirect-uri>" \
-d "client_id=<your-client-id>" \
-d "client_secret=<your-client-secret>"
```

**Python**

```python
import requests

response = requests.post(
  "https://auth.fd.agenticstar.tm.softbank.jp/federation/auth/v1/token",
  data={
      "grant_type": "authorization_code",
      "code": "<auth-code>",
      "redirect_uri": "<your-redirect-uri>",
      "client_id": "<your-client-id>",
      "client_secret": "<your-client-secret>",
  },
)
token = response.json()["access_token"]
print(token)
```

**TypeScript**

```typescript
const response = await fetch(
"https://auth.fd.agenticstar.tm.softbank.jp/federation/auth/v1/token",
{
  method: "POST",
  headers: { "Content-Type": "application/x-www-form-urlencoded" },
  body: new URLSearchParams({
    grant_type: "authorization_code",
    code: "<auth-code>",
    redirect_uri: "<your-redirect-uri>",
    client_id: "<your-client-id>",
    client_secret: "<your-client-secret>",
  }),
}
);

const { access_token } = await response.json();
console.log(access_token);
```

**Go**

```go
package main

import (
  "fmt"
  "net/http"
  "net/url"
  "encoding/json"
)

func main() {
  resp, _ := http.PostForm(
      "https://auth.fd.agenticstar.tm.softbank.jp/federation/auth/v1/token",
      url.Values{
          "grant_type":    {"authorization_code"},
          "code":          {"<auth-code>"},
          "redirect_uri":  {"<your-redirect-uri>"},
          "client_id":     {"<your-client-id>"},
          "client_secret": {"<your-client-secret>"},
      },
  )
  defer resp.Body.Close()

  var result map[string]interface{}
  json.NewDecoder(resp.Body).Decode(&result)
  fmt.Println(result["access_token"])
}
```

### パラメータ

- `grant_type`: `authorization_code` 固定
- `code`: Step 2 で取得した認可コード
- `redirect_uri`: Step 2 と同じ Redirect URI
- `client_id`: Step 1 で確認した Client ID
- `client_secret`: Step 1 で確認した Client Secret

### レスポンス例

```json
{
  "access_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...",
  "id_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...",
  "refresh_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "Bearer",
  "expires_in": 3600,
  "refresh_expires_in": 86400,
  "scope": "openid chat:exec"
}
```

> **トークンの有効期限**
>
> `expires_in` に指定された秒数の間、トークンが有効です。期限切れ後は `refresh_token` を使ってトークンをリフレッシュできます。詳細は[認証ガイド](https://developers.fd.agenticstar.tm.softbank.jp/docs/saas/api/agent/guide/auth-guide.md)を参照してください。

## Step 4: Chat API 呼び出し

取得したアクセストークンを使用して、SSE（Server-Sent Events）経由で Chat API を呼び出します。ストリーム形式でエージェントからのリアルタイム応答を受け取ります。

### リクエスト例

**Create chat completion**

**curl**

```curl
curl -X POST https://api.fd.agenticstar.tm.softbank.jp/api/v1/chat/completions \
-H "Authorization: Bearer <access_token>" \
-H "Content-Type: application/json" \
-d '{
  "model": "AGENTIC STAR",
  "stream": true,
  "messages": [
    {
      "role": "user",
      "content": "こんにちは"
    }
  ]
}'
```

**Python**

```python
import requests
import json

response = requests.post(
  "https://api.fd.agenticstar.tm.softbank.jp/api/v1/chat/completions",
  headers={
      "Authorization": f"Bearer {token}",
      "Content-Type": "application/json",
  },
  json={
      "model": "AGENTIC STAR",
      "stream": True,
      "messages": [{"role": "user", "content": "こんにちは"}],
  },
  stream=True,
)

for line in response.iter_lines():
  if line:
      data = line.decode("utf-8")
      if data == "data: [DONE]":
          break
      if data.startswith("data: "):
          chunk = json.loads(data[6:])
          content = chunk["choices"][0]["delta"].get("content", "")
          print(content, end="", flush=True)
```

**TypeScript**

```typescript
const response = await fetch(
"https://api.fd.agenticstar.tm.softbank.jp/api/v1/chat/completions",
{
  method: "POST",
  headers: {
    "Authorization": `Bearer ${accessToken}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    model: "AGENTIC STAR",
    stream: true,
    messages: [{ role: "user", content: "こんにちは" }],
  }),
}
);

const reader = response.body.getReader();
const decoder = new TextDecoder();

while (true) {
const { done, value } = await reader.read();
if (done) break;
const text = decoder.decode(value);
for (const line of text.split("\n")) {
  if (line.startsWith("data: ") && line !== "data: [DONE]") {
    const chunk = JSON.parse(line.slice(6));
    process.stdout.write(chunk.choices[0]?.delta?.content ?? "");
  }
}
}
```

**Go**

```go
package main

import (
  "bufio"
  "bytes"
  "encoding/json"
  "fmt"
  "net/http"
  "strings"
)

func main() {
  token := "<access_token>" // Step 3 で取得したアクセストークン

  body, _ := json.Marshal(map[string]interface{}{
      "model":  "AGENTIC STAR",
      "stream": true,
      "messages": []map[string]string{
          {"role": "user", "content": "こんにちは"},
      },
  })

  req, _ := http.NewRequest("POST",
      "https://api.fd.agenticstar.tm.softbank.jp/api/v1/chat/completions",
      bytes.NewReader(body))
  req.Header.Set("Authorization", "Bearer "+token)
  req.Header.Set("Content-Type", "application/json")

  resp, _ := http.DefaultClient.Do(req)
  defer resp.Body.Close()

  scanner := bufio.NewScanner(resp.Body)
  for scanner.Scan() {
      line := scanner.Text()
      if strings.HasPrefix(line, "data: ") {
          data := line[6:]
          if data == "[DONE]" { break }
          var chunk map[string]interface{}
          json.Unmarshal([]byte(data), &chunk)
          choices, _ := chunk["choices"].([]interface{})
          if len(choices) > 0 {
              delta, _ := choices[0].(map[string]interface{})["delta"].(map[string]interface{})
              if content, ok := delta["content"].(string); ok {
                  fmt.Print(content)
              }
          }
      }
  }
}
```

### パラメータ

- `<access_token>`: Step 3 で取得したアクセストークン
- `stream: true`: SSE ストリーミングを有効化
- `messages`: ユーザーからのメッセージ。配列形式で複数メッセージも可能

### レスポンス例（SSE ストリーム）

```text
data: {"choices":[{"delta":{"content":"こんにちは"}}]}

data: {"choices":[{"delta":{"content":"、お手伝い"}}]}

data: {"choices":[{"delta":{"content":"できることはありますか"}}]}

data: [DONE]
```

上記は読みやすさのため `delta.content` のみを抜粋しています。実際のチャンクには `createdAt` / `model` / `choices[].index` / `finishReason` などの追加フィールドが含まれます。完全なフォーマットは [API リファレンス](https://developers.fd.agenticstar.tm.softbank.jp/docs/saas/api/agent/reference/api-reference.md#chat) を参照してください。

> **SSE ストリーミングについて**
>
> レスポンスは Server-Sent Events（SSE）形式で、チャンク単位でリアルタイムに送信されます。各チャンクは `data: JSON` 形式です。`data: [DONE]` で会話が完了します。詳細は [ストリーミングガイド](https://developers.fd.agenticstar.tm.softbank.jp/docs/saas/api/agent/guide/streaming-guide.md) を参照してください。

## 次のステップ

さらに詳しい情報と実装パターンについて、以下のドキュメントを参照してください。

[Consoleガイド→](https://developers.fd.agenticstar.tm.softbank.jp/docs/saas/api/agent/guide/console-guide.md)

[アプリケーション作成・スコープ設定・認証情報の取得](https://developers.fd.agenticstar.tm.softbank.jp/docs/saas/api/agent/guide/console-guide.md)

[認証ガイド→](https://developers.fd.agenticstar.tm.softbank.jp/docs/saas/api/agent/guide/auth-guide.md)

[認証フローの詳細・トークンリフレッシュ](https://developers.fd.agenticstar.tm.softbank.jp/docs/saas/api/agent/guide/auth-guide.md)

[接続方式ガイド→](https://developers.fd.agenticstar.tm.softbank.jp/docs/saas/api/agent/guide/connection-guide.md)

[SSE・MCP・A2A の比較と選択ガイド](https://developers.fd.agenticstar.tm.softbank.jp/docs/saas/api/agent/guide/connection-guide.md)

[ストリーミングガイド→](https://developers.fd.agenticstar.tm.softbank.jp/docs/saas/api/agent/guide/streaming-guide.md)

[SSE接続ライフサイクル・イベント処理・再接続・エラーハンドリング](https://developers.fd.agenticstar.tm.softbank.jp/docs/saas/api/agent/guide/streaming-guide.md)
