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

# Stream connect

> Returns a direct WebSocket URL and a short-lived token that opens connections there.

Returns a direct WebSocket URL and a connect token. A connection opened at that URL does not pass through `api.metastreams.io`. Its frames, limits and billing are the same as on [`/v1/stream`](https://docs.metastreams.io/streams/overview). The request requires an API key and costs no credit. [Routes](https://docs.metastreams.io/streams/overview.md#routes) describes when to use it.

## Response

* `url` is the WebSocket URL to connect to, such as `wss://<host>:<port>/v1/stream`. Use it exactly as returned.
* `token` is an opaque string that starts with `metaconnect_`. Send it as `Authorization: Bearer <token>` in the WebSocket handshake. Treat it as a secret.
* `expiresAt` is the token's expiry time in Unix milliseconds, 30 seconds after the response. The token opens any number of connections until then, within the key's limit of 20.

The token is not accepted on any REST endpoint or on `/v1/stream` at `api.metastreams.io`.

## Errors

| Code | When |
| - | - |
| `FORBIDDEN` | The request used a session token instead of an API key, or the organization's plan does not include streams |
| `ORIGIN_NOT_ALLOWED` | The request used a session token from an origin that the token does not allow |
| `NOT_FOUND` | No direct URL is available. Connect to `wss://api.metastreams.io/v1/stream` instead. |

```bash cURL theme={null}
curl -X POST "https://api.metastreams.io/v1/stream/connect" \
  -H "Authorization: Bearer $API_KEY"
```

```typescript Node.js theme={null}
import WebSocket from "ws";

const response = await fetch("https://api.metastreams.io/v1/stream/connect", {
  method: "POST",
  headers: { Authorization: `Bearer ${process.env.API_KEY}` },
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const { url, token } = await response.json();

const socket = new WebSocket(url, { headers: { Authorization: `Bearer ${token}` } });
socket.on("error", (error) => console.error("stream error:", error.message));
```

```rust Rust theme={null}
use serde_json::Value;
use tokio_tungstenite::connect_async;
use tokio_tungstenite::tungstenite::client::IntoClientRequest;

let answer: Value = reqwest::Client::new()
    .post("https://api.metastreams.io/v1/stream/connect")
    .bearer_auth(std::env::var("API_KEY")?)
    .send()
    .await?
    .error_for_status()?
    .json()
    .await?;

let mut request = answer["url"].as_str().ok_or("no url")?.into_client_request()?;
let token = answer["token"].as_str().ok_or("no token")?;
request.headers_mut().insert("Authorization", format!("Bearer {token}").parse()?);
let (socket, _) = connect_async(request).await?;
```

```json Created theme={null}
{
  "url": "wss://<host>:<port>/v1/stream",
  "token": "metaconnect_AbC...",
  "expiresAt": 1789632915120
}
```


## OpenAPI

````yaml specs/openapi.json POST /v1/stream/connect
openapi: 3.1.0
info:
  title: Metastreams API
  description: >-
    The Metastreams market-data API. Amounts are decimal strings, timestamps are
    Unix milliseconds, and every field name is camelCase.
  license:
    name: Proprietary
  version: 1.0.0
servers:
  - url: https://{host}
    variables:
      host:
        default: api.metastreams.io
        description: API host.
security:
  - bearerKey: []
paths:
  /v1/stream/connect:
    post:
      tags:
        - stream
      summary: Issue a direct stream URL and a connect token.
      description: >-
        A backend calls this with its API key. It then opens the stream socket
        at `url` before

        `expiresAt`, with `token` as its bearer credential. The socket connects
        to the server that

        answered the call, with no proxy between. Its frames, limits and billing
        are those of

        `GET /v1/stream`. One token opens sockets until it expires, within the
        key's socket limit.
      operationId: stream_connect
      responses:
        '201':
          description: >-
            The direct stream URL, and the token that opens a socket there
            within 30 seconds. The call costs no credit.
          headers:
            X-Credits-Cost:
              schema:
                type: integer
              description: >-
                Credits charged for this request. Zero on any non-2xx. Sent on a
                metered tier only.
            X-Credits-Remaining:
              schema:
                type: integer
              description: Credit balance after this request. Sent on a metered tier only.
            X-RateLimit-Remaining:
              schema:
                type: integer
              description: >-
                Requests left in the bucket this request spent from. Not sent
                with a 401.
            X-Request-ID:
              schema:
                type: string
              description: >-
                This request's trace ID. Echoed from the request, or generated
                when it sent none.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/UiStreamConnection'
        '401':
          description: >-
            Missing or invalid credential: an API key, or a session token a key
            minted.
          headers:
            X-Credits-Cost:
              schema:
                type: integer
              description: >-
                Credits charged for this request. Zero on any non-2xx. Sent on a
                metered tier only.
            X-Credits-Remaining:
              schema:
                type: integer
              description: Credit balance after this request. Sent on a metered tier only.
            X-RateLimit-Remaining:
              schema:
                type: integer
              description: >-
                Requests left in the bucket this request spent from. Not sent
                with a 401.
            X-Request-ID:
              schema:
                type: string
              description: >-
                This request's trace ID. Echoed from the request, or generated
                when it sent none.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
        '402':
          description: >-
            The organization's credits this billing period reach its plan's
            limit.
          headers:
            X-Credits-Cost:
              schema:
                type: integer
              description: >-
                Credits charged for this request. Zero on any non-2xx. Sent on a
                metered tier only.
            X-Credits-Remaining:
              schema:
                type: integer
              description: Credit balance after this request. Sent on a metered tier only.
            X-RateLimit-Remaining:
              schema:
                type: integer
              description: >-
                Requests left in the bucket this request spent from. Not sent
                with a 401.
            X-Request-ID:
              schema:
                type: string
              description: >-
                This request's trace ID. Echoed from the request, or generated
                when it sent none.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
        '403':
          description: >-
            Only a key asks: a session token answers `FORBIDDEN`, or
            `ORIGIN_NOT_ALLOWED` from an origin it does not name. A key whose
            plan sells no streams answers `FORBIDDEN` too.
          headers:
            X-Credits-Cost:
              schema:
                type: integer
              description: >-
                Credits charged for this request. Zero on any non-2xx. Sent on a
                metered tier only.
            X-Credits-Remaining:
              schema:
                type: integer
              description: Credit balance after this request. Sent on a metered tier only.
            X-RateLimit-Remaining:
              schema:
                type: integer
              description: >-
                Requests left in the bucket this request spent from. Not sent
                with a 401.
            X-Request-ID:
              schema:
                type: string
              description: >-
                This request's trace ID. Echoed from the request, or generated
                when it sent none.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
        '404':
          description: The site has no direct stream; open `GET /v1/stream`.
          headers:
            X-Credits-Cost:
              schema:
                type: integer
              description: >-
                Credits charged for this request. Zero on any non-2xx. Sent on a
                metered tier only.
            X-Credits-Remaining:
              schema:
                type: integer
              description: Credit balance after this request. Sent on a metered tier only.
            X-RateLimit-Remaining:
              schema:
                type: integer
              description: >-
                Requests left in the bucket this request spent from. Not sent
                with a 401.
            X-Request-ID:
              schema:
                type: string
              description: >-
                This request's trace ID. Echoed from the request, or generated
                when it sent none.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
        '429':
          description: Rate limit exceeded.
          headers:
            Retry-After:
              schema:
                type: integer
              description: Seconds to wait before retrying.
            X-Credits-Cost:
              schema:
                type: integer
              description: >-
                Credits charged for this request. Zero on any non-2xx. Sent on a
                metered tier only.
            X-Credits-Remaining:
              schema:
                type: integer
              description: Credit balance after this request. Sent on a metered tier only.
            X-RateLimit-Remaining:
              schema:
                type: integer
              description: >-
                Requests left in the bucket this request spent from. Not sent
                with a 401.
            X-Request-ID:
              schema:
                type: string
              description: >-
                This request's trace ID. Echoed from the request, or generated
                when it sent none.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
        '500':
          description: Unexpected server failure.
          headers:
            X-Credits-Cost:
              schema:
                type: integer
              description: >-
                Credits charged for this request. Zero on any non-2xx. Sent on a
                metered tier only.
            X-Credits-Remaining:
              schema:
                type: integer
              description: Credit balance after this request. Sent on a metered tier only.
            X-RateLimit-Remaining:
              schema:
                type: integer
              description: >-
                Requests left in the bucket this request spent from. Not sent
                with a 401.
            X-Request-ID:
              schema:
                type: string
              description: >-
                This request's trace ID. Echoed from the request, or generated
                when it sent none.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
        '503':
          description: Dependency down or maintenance.
          headers:
            X-Credits-Cost:
              schema:
                type: integer
              description: >-
                Credits charged for this request. Zero on any non-2xx. Sent on a
                metered tier only.
            X-Credits-Remaining:
              schema:
                type: integer
              description: Credit balance after this request. Sent on a metered tier only.
            X-RateLimit-Remaining:
              schema:
                type: integer
              description: >-
                Requests left in the bucket this request spent from. Not sent
                with a 401.
            X-Request-ID:
              schema:
                type: string
              description: >-
                This request's trace ID. Echoed from the request, or generated
                when it sent none.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorEnvelope'
components:
  schemas:
    UiStreamConnection:
      type: object
      description: Where to open the stream socket directly, and the token that opens it.
      required:
        - url
        - token
        - expiresAt
      properties:
        expiresAt:
          $ref: '#/components/schemas/UnixMilliseconds'
          description: When the token stops opening sockets.
        token:
          type: string
          description: >-
            The token that opens sockets at `url`, as `Authorization: Bearer
            <token>`.
        url:
          type: string
          description: The answering site's direct stream URL.
          example: wss://stream-<region>.metastreams.io:9443/v1/stream
    ErrorEnvelope:
      type: object
      description: The complete error response body — every error is exactly this.
      required:
        - error
      properties:
        error:
          $ref: '#/components/schemas/ErrorDetail'
          description: The error.
    UnixMilliseconds:
      type: integer
      format: int64
      description: An instant, as milliseconds since the Unix epoch.
    ErrorDetail:
      type: object
      description: The `error` object inside the envelope.
      required:
        - code
        - message
      properties:
        code:
          $ref: '#/components/schemas/ErrorCode'
          description: >-
            Stable, machine-readable. Clients switch on this, never on
            `message`.
        details:
          description: Optional; shape is fixed per code.
        message:
          type: string
          description: |-
            Human-readable, written for the integrating developer:
            `[What happened]. [What to do next — if actionable].`
    ErrorCode:
      type: string
      description: |-
        Every wire error code the API can return.

        Append-only: a new code is non-breaking, since clients fall back on the
        HTTP status for one they do not recognize, and a published code is never
        renamed or removed.
      enum:
        - UNAUTHORIZED
        - FORBIDDEN
        - VALIDATION_ERROR
        - UNSUPPORTED_CHAIN
        - NOT_FOUND
        - RATE_LIMITED
        - CREDITS_EXHAUSTED
        - INTERNAL_ERROR
        - SERVICE_UNAVAILABLE
        - RANGE_TOO_LARGE
        - INVALID_CREDENTIALS
        - ORIGIN_NOT_ALLOWED
        - NOT_ORG_MEMBER
        - MEMBERSHIP_INACTIVE
        - EMAIL_NOT_VERIFIED
        - EMAIL_TAKEN
        - ALREADY_MEMBER
        - INVITATION_ALREADY_SENT
        - INVITATION_ALREADY_ACCEPTED
        - LAST_ADMIN
        - CANNOT_REMOVE_SELF
        - KEY_LIMIT_REACHED
        - TOKEN_EXPIRED
        - PAYLOAD_TOO_LARGE
        - UNSUPPORTED_MEDIA_TYPE
        - IMAGE_TOO_LARGE
        - DEMO_LIMIT_REACHED
        - DEMO_BUILD_IN_FLIGHT
        - DEMO_CHALLENGE_FAILED
        - STAFF_ADMIN_REQUIRED
        - DEMO_PUBLISH_LIMIT_REACHED
  securitySchemes:
    bearerKey:
      type: http
      scheme: bearer
      description: >-
        Send an API key, or a session token a key minted, as `Authorization:
        Bearer <credential>`. A browser opening `/v1/stream` offers its session
        token in `Sec-WebSocket-Protocol` instead.

````

This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.