# Call the API

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

## Introduction

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

> **Prerequisites**
>
> - Setup of the AGENTIC STAR environment purchased from Marketplace is complete
> - A service account has been created in the admin console
> - You have Base URL, Client ID, Client Secret, and Agent ID

## Step 1: Verify Authentication Information

Gather the information you need to call the Chat API from your administrator and the admin console. Note that these values are retrieved from different places.

### From your administrator

- **Base URL** — Domain of the external API (`https://<your-domain>`). The administrator decided it when the environment was built
- **Authentication service domain** — Where you obtain the token (`https://<auth-domain>`). The administrator decided it when the environment was built

### From the Service Account detail screen

- **Client ID** — Client ID issued for the service account
- **Client Secret** — Secret issued for the service account

### From the admin console

- **Agent ID** — Identifier to pass as the `agentId` parameter in Chat API calls. Available on the detail page of the target agent under **Agent Management → Agent Settings** in the admin console (see [Settings Guide — Agent Settings](https://developers.fd.agenticstar.tm.softbank.jp/en/docs/marketplace/basic/build/guide/settings-guide.md#agent-settings)).

### Authentication Information Example

```text
Base URL: https://<your-domain>
Auth URL: https://<auth-domain>
Client ID: mp-service-001
Client Secret: (hidden)
Agent ID: agent-ai-bot
```

## Step 2: Obtain Token

Use the Client Credentials flow to obtain an access token. Execute the following request from your server.

### Request Example

**Obtain access token**

**curl**

```curl
curl -X POST https://<auth-domain>/api/v1/auth/external-service-token \
-H "Content-Type: application/json" \
-d '{
  "client_id": "<your-client-id>",
  "client_secret": "<your-client-secret>"
}'
```

**Python**

```python
import requests

response = requests.post(
  "https://<auth-domain>/api/v1/auth/external-service-token",
  json={
      "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-domain>/api/v1/auth/external-service-token",
{
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    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 (
  "bytes"
  "encoding/json"
  "fmt"
  "net/http"
)

func main() {
  body, _ := json.Marshal(map[string]string{
      "client_id":     "<your-client-id>",
      "client_secret": "<your-client-secret>",
  })

  resp, _ := http.Post(
      "https://<auth-domain>/api/v1/auth/external-service-token",
      "application/json",
      bytes.NewReader(body),
  )
  defer resp.Body.Close()

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

### Parameters

- `<auth-domain>`: Authentication service domain verified in Step 1 (example: auth.example.com)
- `<your-client-id>`: Client ID verified in Step 1
- `<your-client-secret>`: Secret verified in Step 1

### Response Example

```json
{
  "success": true,
  "access_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...",
  "token_type": "Bearer",
  "expires_in": 86400,
  "scope": "openid profile email"
}
```

> **Token Expiration**
>
> The token is valid for the number of seconds specified in `expires_in`. Obtain a new token before expiration. The Client Credentials flow does not issue refresh tokens, so after expiration, execute the same request again.

## Step 3: 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://<your-domain>/api/v1/chat/completions \
-H "Authorization: Bearer <access_token>" \
-H "Content-Type: application/json" \
-d '{
  "model": "AGENTIC STAR",
  "stream": true,
  "agentId": "<your-agent-id>",
  "messages": [
    {
      "role": "user",
      "content": "Hello"
    }
  ]
}'
```

**Python**

```python
import requests
import json

response = requests.post(
  "https://<your-domain>/api/v1/chat/completions",
  headers={
      "Authorization": f"Bearer {token}",
      "Content-Type": "application/json",
  },
  json={
      "model": "AGENTIC STAR",
      "stream": True,
      "agentId": "<your-agent-id>",
      "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://<your-domain>/api/v1/chat/completions",
{
  method: "POST",
  headers: {
    "Authorization": `Bearer ${accessToken}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    model: "AGENTIC STAR",
    stream: true,
    agentId: "<your-agent-id>",
    messages: [{ role: "user", content: "Hello" }],
  }),
}
);

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

while (true) {
const { done, value } = await reader?.read() || { done: true };
if (done) break;
for (const line of decoder.decode(value).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 2

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

  req, _ := http.NewRequest("POST",
      "https://<your-domain>/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 2
- `<your-agent-id>`: Agent ID verified in Step 1
- `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/marketplace/basic/api/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/marketplace/basic/api/guide/streaming-guide.md) for details.

## Next Steps

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

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

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

[System Integration API Reference→](https://developers.fd.agenticstar.tm.softbank.jp/en/docs/marketplace/basic/api/reference/api-reference.md)

[Endpoint specifications, request/response formats, error codes](https://developers.fd.agenticstar.tm.softbank.jp/en/docs/marketplace/basic/api/reference/api-reference.md)

[Authentication API Reference (MP)→](https://developers.fd.agenticstar.tm.softbank.jp/en/docs/marketplace/basic/api/reference/auth-mp-ref.md)

[JWT structure and token retrieval specifications](https://developers.fd.agenticstar.tm.softbank.jp/en/docs/marketplace/basic/api/reference/auth-mp-ref.md)
