> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.beatapi.io/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.beatapi.io/_mcp/server.

# Realtime API

POST https://api.beatapi.io/v1/realtime/sessions
Content-Type: application/json

Create a short-lived Realtime API browser session and receive a client secret for the BeatAPI realtime SDK.

Create the Session on your trusted server, pass only `client_secret` to the browser, connect with `@beatapi/realtime`, and close the Session when the experience ends. See the [Quick Guide](/quick-guide) for the security and lifecycle checklist.

Reference: https://docs.beatapi.io/api-reference/realtime-api

## Authentication

- `Authorization` header (bearer token, required) — Send your API key as `Authorization: Bearer <BEATAPI_API_KEY>`.

## Request

### Headers

- `Idempotency-Key` (string, required)

### Body (application/json)

This endpoint expects an object.

- `max_duration_seconds` (enum, required) — Required maximum live session duration in seconds. The USD amount is reserved for the selected 15, 60, or 300 second tier.
  - Allowed values: `15`, `60`, `300`
- `allowed_origins` (list of string, required) — Exact browser origins allowed to use the short-lived session secret.
- `metadata` (map from string to string, optional) — Optional server-defined string metadata for your own correlation. Up to 20 keys; keys are at most 64 characters and values at most 256 characters.

## Response

### 201

Realtime session created

- `data` (RealtimeSessionCreated, required) — Created Realtime Session including the one-time short-lived browser credential.

## Errors

### 400 Bad Request Error

Malformed JSON or a field, value or combination this endpoint does not accept (`bad_request`; the message names the field), or input refused by moderation (`content_policy_violation`). Not retryable unchanged.

- `error` (ErrorError, required) — Structured BeatAPI error. Use `code` (or `retryable`) for program logic and retain `request_id` for support.

### 401 Unauthorized Error

No API key (`missing_api_key`), or a key that is wrong, expired, disabled or exhausted (`invalid_api_key`; the message says which). Send it as `Authorization: Bearer <key>`; the key works with or without the `sk-` prefix. Not retryable.

- `error` (ErrorError, required) — Structured BeatAPI error. Use `code` (or `retryable`) for program logic and retain `request_id` for support.

### 402 Payment Required Error

Insufficient balance (`insufficient_credits`). The account balance is zero or below the price of this request. Top up, then send it again; not retryable before that.

- `error` (ErrorError, required) — Structured BeatAPI error. Use `code` (or `retryable`) for program logic and retain `request_id` for support.

### 409 Conflict Error

The `Idempotency-Key` was already used with a different request body, or the first request with it is still being processed (`idempotency_conflict`). Not retryable unchanged.

- `error` (ErrorError, required) — Structured BeatAPI error. Use `code` (or `retryable`) for program logic and retain `request_id` for support.

### 429 Too Many Requests Error

Too many requests (`rate_limit_exceeded`, including the free-model limits) or too many tasks processing at once (`user_concurrency_exceeded`). Retryable after `Retry-After` seconds (also `error.retry_after_seconds`).

- `error` (ErrorError, required) — Structured BeatAPI error. Use `code` (or `retryable`) for program logic and retain `request_id` for support.

### 503 Service Unavailable Error

Realtime is disabled for the account (`realtime_disabled`, not retryable) or capacity is temporarily unavailable (`realtime_capacity_unavailable`, retryable after `Retry-After` seconds).

- `error` (ErrorError, required) — Structured BeatAPI error. Use `code` (or `retryable`) for program logic and retain `request_id` for support.

## Types

### RealtimeSessionCreated

- `id` (string, required) — Stable Realtime Session ID used to inspect or close the session.
- `object` (enum, required) — Object discriminator; always `realtime.session`.
  - Allowed values: `realtime.session`
- `status` (enum, required) — Active means BeatAPI accepted the first billing heartbeat after remote output began.
  - Allowed values: `ready`, `connecting`, `active`, `closed`, `failed`, `expired`
- `expires_at` (datetime, required) — Time when the unconnected short-lived session credential expires.
- `max_duration_seconds` (enum, required) — Maximum selected live duration and billing tier in seconds.
  - Allowed values: `15`, `60`, `300`
- `allowed_origins` (list of string, required) — Exact browser origins authorized to use this Session.
- `credits` (RealtimeSessionCreatedCredits, required) — USD reservation, settlement, and refund lifecycle for this Realtime Session. Compatibility field names are retained.
- `request_id` (string, required) — Correlation ID to retain for logs and BeatAPI support.
- `created_at` (datetime, required) — Time when the Session was created.
- `connected_at` (datetime, required, nullable) — Time of the first accepted BeatAPI billing heartbeat; null before billing activation.
- `closed_at` (datetime, required, nullable) — Time when the Session closed, or null while it remains open.
- `client_secret` (string, required) — Short-lived BeatAPI browser credential returned only by POST. Never expose an sk_ API key to the browser.

### ErrorError

Structured BeatAPI error. Use `code` (or `retryable`) for program logic and retain `request_id` for support.

- `code` (enum, required) — Stable machine-readable error code. `unauthorized` is the deprecated name for a 401; since 2026-09-29 a 401 is `missing_api_key` or `invalid_api_key`. Treat a legacy `unauthorized` like `invalid_api_key`.
  - Allowed values: `bad_request`, `missing_api_key`, `invalid_api_key`, `unauthorized`, `forbidden`, `not_found`, `insufficient_credits`, `idempotency_conflict`, `user_concurrency_exceeded`, `rate_limit_exceeded`, `content_policy_violation`, `processing_unavailable`, `processing_failed`, `processing_timeout`, `result_transfer_failed`, `invalid_signature`, `realtime_disabled`, `realtime_capacity_unavailable`, `realtime_session_expired`, `origin_not_allowed`, `invalid_client_secret`, `transport_not_allowed`, `internal_error`
- `message` (string, required) — English sentence that states the cause; for `bad_request` it names the field. Written for people and logs, not for parsing.
- `retryable` (boolean, required) — Whether making the same call again could succeed. Present on every error; branch on it instead of the status code. True for 429, 500 and 503 (rate_limit_exceeded, user_concurrency_exceeded, internal_error, processing_unavailable, processing_timeout, processing_failed, result_transfer_failed, realtime_capacity_unavailable). False for a request, key or balance that must change first (bad_request, content_policy_violation, missing_api_key, invalid_api_key, insufficient_credits, forbidden, not_found, idempotency_conflict, realtime_disabled and the other realtime credential codes).
- `request_id` (string, required) — Correlation ID to retain for BeatAPI support.
- `retry_after_seconds` (integer, optional) — Seconds to wait before retrying. Present on every 429, and on a 503 when the wait is known; the same value is sent in the `Retry-After` header.
- `docs` (string, optional) — The public Skill page that says what to do about an error. Present on errors answered by the capability endpoints (`/v1/capabilities/search`, `/v1/capabilities/inspect`, `/v1/capabilities/run`); absent on every other endpoint.

### RealtimeSessionCreatedCredits

USD reservation, settlement, and refund lifecycle for this Realtime Session. Compatibility field names are retained.

- `reserved` (double, required) — USD amount reserved when the Session is created.
- `settled` (double, required) — USD amount settled after the first accepted billing heartbeat.
- `refunded` (double, required) — USD amount refunded if the Session ends without billing activation.

## Examples

**Request**

```json
{
  "max_duration_seconds": 60,
  "allowed_origins": [
    "https://app.example.com"
  ],
  "metadata": {
    "customer_id": "cus_123"
  }
}
```

**Response**

```json
{
  "data": {
    "id": "rts_8K2qA",
    "object": "realtime.session",
    "status": "ready",
    "expires_at": "2026-08-12T10:01:00.000Z",
    "max_duration_seconds": 60,
    "allowed_origins": [
      "https://app.example.com"
    ],
    "credits": {
      "reserved": 1.2,
      "settled": 0,
      "refunded": 0
    },
    "request_id": "req_abc123",
    "created_at": "2026-08-12T10:00:00.000Z",
    "connected_at": null,
    "closed_at": null,
    "client_secret": "brt_live_example_short_lived_secret"
  }
}
```

**SDK Code**

```python Realtime API
import requests

url = "https://api.beatapi.io/v1/realtime/sessions"

payload = {
    "max_duration_seconds": 60,
    "allowed_origins": ["https://app.example.com"],
    "metadata": { "customer_id": "cus_123" }
}
headers = {
    "Idempotency-Key": "rts-create-cus_123-01",
    "Authorization": "Bearer <token>",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
```

```javascript Realtime API
const url = 'https://api.beatapi.io/v1/realtime/sessions';
const options = {
  method: 'POST',
  headers: {
    'Idempotency-Key': 'rts-create-cus_123-01',
    Authorization: 'Bearer <token>',
    'Content-Type': 'application/json'
  },
  body: '{"max_duration_seconds":60,"allowed_origins":["https://app.example.com"],"metadata":{"customer_id":"cus_123"}}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go Realtime API
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://api.beatapi.io/v1/realtime/sessions"

	payload := strings.NewReader("{\n  \"max_duration_seconds\": 60,\n  \"allowed_origins\": [\n    \"https://app.example.com\"\n  ],\n  \"metadata\": {\n    \"customer_id\": \"cus_123\"\n  }\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Idempotency-Key", "rts-create-cus_123-01")
	req.Header.Add("Authorization", "Bearer <token>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby Realtime API
require 'uri'
require 'net/http'

url = URI("https://api.beatapi.io/v1/realtime/sessions")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["Idempotency-Key"] = 'rts-create-cus_123-01'
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"max_duration_seconds\": 60,\n  \"allowed_origins\": [\n    \"https://app.example.com\"\n  ],\n  \"metadata\": {\n    \"customer_id\": \"cus_123\"\n  }\n}"

response = http.request(request)
puts response.read_body
```

```java Realtime API
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.beatapi.io/v1/realtime/sessions")
  .header("Idempotency-Key", "rts-create-cus_123-01")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"max_duration_seconds\": 60,\n  \"allowed_origins\": [\n    \"https://app.example.com\"\n  ],\n  \"metadata\": {\n    \"customer_id\": \"cus_123\"\n  }\n}")
  .asString();
```

```php Realtime API
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.beatapi.io/v1/realtime/sessions', [
  'body' => '{
  "max_duration_seconds": 60,
  "allowed_origins": [
    "https://app.example.com"
  ],
  "metadata": {
    "customer_id": "cus_123"
  }
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
    'Idempotency-Key' => 'rts-create-cus_123-01',
  ],
]);

echo $response->getBody();
```

```csharp Realtime API
using RestSharp;

var client = new RestClient("https://api.beatapi.io/v1/realtime/sessions");
var request = new RestRequest(Method.POST);
request.AddHeader("Idempotency-Key", "rts-create-cus_123-01");
request.AddHeader("Authorization", "Bearer <token>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"max_duration_seconds\": 60,\n  \"allowed_origins\": [\n    \"https://app.example.com\"\n  ],\n  \"metadata\": {\n    \"customer_id\": \"cus_123\"\n  }\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift Realtime API
import Foundation

let headers = [
  "Idempotency-Key": "rts-create-cus_123-01",
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = [
  "max_duration_seconds": 60,
  "allowed_origins": ["https://app.example.com"],
  "metadata": ["customer_id": "cus_123"]
] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://api.beatapi.io/v1/realtime/sessions")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```