# Call the API

This guide walks you through obtaining a token using Authorization Code authentication and conversing with an agent via SSE.

## Introduction

Here are the quickest steps to use the SaaS API. You can start conversing with an agent in just four steps.

> **Scope of this Quickstart**
>
> This quickstart targets **Web applications** (Confidential Clients that can keep a `Client Secret` on the server side). For SPAs / mobile apps (Public Clients), the PKCE flow is required, so this quickstart cannot be used as-is. See the [Authentication Guide](https://developers.fd.agenticstar.tm.softbank.jp/en/docs/saas/api/agent/guide/auth-guide.md) for details.
>
> The steps on this page (chat) cannot be done with a token of a system integration (server-to-server, Client Credentials flow). For how to obtain a system integration token, see [Authentication Guide — Client Credentials Flow](https://developers.fd.agenticstar.tm.softbank.jp/en/docs/saas/api/agent/guide/auth-guide.md#client-credentials-flow). To operate on projects from an external system, see [User API Reference — Projects](https://developers.fd.agenticstar.tm.softbank.jp/en/docs/saas/api/agent/reference/api-reference.md#projects) for applications, or [System Integration API Reference — Projects](https://developers.fd.agenticstar.tm.softbank.jp/en/docs/saas/api/agent/reference/admin-api-reference.md#projects) for system integrations.

> **Prerequisites**
>
> - API option subscription is activated
>
> - Ability to log in to Console (developer role or higher)
>
> - A **Web application** type client has been created in Console ([Console Guide](https://developers.fd.agenticstar.tm.softbank.jp/en/docs/saas/api/agent/guide/console-guide.md))
>
> - You have obtained the following information:
>
>   <!-- -->
>
>   - `Client ID` - The ID of the created application
>   - `Client Secret` - The application secret
>   - `Redirect URI` - The redirect URL registered in Console

## Step 1: Verify Authentication Information

Verify the following information on the app detail screen in Console.

### Example

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

## Step 2: Obtain Authorization Code

Access the authorization endpoint in your browser, log in, and obtain an authorization code.

### Construct Authorization URL

Open the following URL in your browser. Replace `client_id`, `redirect_uri`, and `state` with your own values.

```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>
```

### Parameters

- `response_type`: Fixed as `code`
- `client_id`: Client ID verified in Step 1
- `redirect_uri`: Redirect URI registered in Console (URL-encoded)
- `state`: Random string for CSRF protection (strongly recommended)

### Login and Authorization

1. A login screen appears in the browser. Log in with your usual account.
2. If the application has the consent screen enabled, it is displayed on first use or when scopes are added. Review the content and grant permission.

### Receive Authorization Code

After authorization, the browser redirects to `redirect_uri`. The `code` parameter in the URL is the authorization code.

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

> **warning**
>
> - If `state` is specified, always verify that the value in the response matches the value from your request (CSRF protection)
> - The authorization code has a short expiration, so exchange it for a token immediately in the next step

## Step 3: Obtain Token

Exchange the authorization code for an access token. Execute the following request from your server.

### Request Example

**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"])
}
```

### Parameters

- `grant_type`: Fixed as `authorization_code`
- `code`: Authorization code obtained in Step 2
- `redirect_uri`: Same Redirect URI as Step 2
- `client_id`: Client ID verified in Step 1
- `client_secret`: Client Secret verified in Step 1

### Response Example

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

> **Token Expiration**
>
> The token is valid for the number of seconds specified in `expires_in`. After expiration, you can refresh the token using `refresh_token`. See the [Authentication Guide](https://developers.fd.agenticstar.tm.softbank.jp/en/docs/saas/api/agent/guide/auth-guide.md) for details.

## Step 4: Call Chat API

Use the obtained access token to call the Chat API via SSE (Server-Sent Events). You will receive real-time responses from the agent in stream format.

### Request Example

**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": "Hello"
    }
  ]
}'
```

**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": "Hello"}],
  },
  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: "Hello" }],
  }),
}
);

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>" // Access token obtained in Step 3

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

  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)
              }
          }
      }
  }
}
```

### Parameters

- `<access_token>`: Access token obtained in Step 3
- `stream: true`: Enable SSE streaming
- `messages`: Message from user. Multiple messages can be sent in array format

### Response Example (SSE Stream)

```text
data: {"choices":[{"delta":{"content":"Hello"}}]}

data: {"choices":[{"delta":{"content":", how can I"}}]}

data: {"choices":[{"delta":{"content":"help you?"}}]}

data: [DONE]
```

For readability, the snippet above only shows `delta.content`. Actual chunks include additional fields such as `createdAt` / `model` / `choices[].index` / `finishReason`. See the [API Reference](https://developers.fd.agenticstar.tm.softbank.jp/en/docs/saas/api/agent/reference/api-reference.md#chat) for the complete format.

> **About SSE Streaming**
>
> The response is in Server-Sent Events (SSE) format, sent in real-time in chunks. Each chunk is in the format `data: JSON`. The conversation completes with `data: [DONE]`. See [Streaming Guide](https://developers.fd.agenticstar.tm.softbank.jp/en/docs/saas/api/agent/guide/streaming-guide.md) for details.

## Next Steps

For more detailed information and implementation patterns, see the following documentation.

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

[Application creation, scope settings, and authentication information](https://developers.fd.agenticstar.tm.softbank.jp/en/docs/saas/api/agent/guide/console-guide.md)

[Authentication Guide→](https://developers.fd.agenticstar.tm.softbank.jp/en/docs/saas/api/agent/guide/auth-guide.md)

[Authentication flow details and token refresh](https://developers.fd.agenticstar.tm.softbank.jp/en/docs/saas/api/agent/guide/auth-guide.md)

[Connection Guide→](https://developers.fd.agenticstar.tm.softbank.jp/en/docs/saas/api/agent/guide/connection-guide.md)

[Compare and choose SSE, MCP, and A2A](https://developers.fd.agenticstar.tm.softbank.jp/en/docs/saas/api/agent/guide/connection-guide.md)

[Streaming Guide→](https://developers.fd.agenticstar.tm.softbank.jp/en/docs/saas/api/agent/guide/streaming-guide.md)

[SSE connection lifecycle, event handling, reconnection, error handling](https://developers.fd.agenticstar.tm.softbank.jp/en/docs/saas/api/agent/guide/streaming-guide.md)
