> For the complete documentation index, see [llms.txt](https://thegrid.ai/docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://thegrid.ai/docs/start-here/programmatic-onboarding.md).

# Programmatic onboarding

Use this path when an **agent**, **CI job**, or **integration** should set up The Grid over HTTP, without copying secrets from the dashboard.

For 99% of programmatic onboarding the flow is three steps: log in with OAuth, create a consumption API key, make your first inference request. Trading setup is optional and covered at the end.

## Prerequisites

* A Grid account at [app.thegrid.ai](https://app.thegrid.ai)
* An OAuth `client_id` (see below)
* A browser or human step to approve the device login once per grant

### Picking a client\_id

Device flow requests identify your integration with a `client_id` for a registered OAuth application:

* **CLI and personal agent flows:** use the public client `grid-cli-public`. It is the application behind the Grid CLI and works for device login today.
* **Server-side products and integrations:** register a dedicated OAuth application so grants show your product's name. Contact <support@thegrid.ai> to register one; self-serve app registration is not available yet.

Check which scopes a client may request before you start:

```bash
curl -sS "https://platform.api.thegrid.ai/v1/oauth/scopes?client_id=grid-cli-public"
```

## Production URLs

| Surface                                                                     | Base URL                             |
| --------------------------------------------------------------------------- | ------------------------------------ |
| [Consumption API](/docs/api-reference/consumption-api.md) (inference)       | `https://api.thegrid.ai/v1`          |
| [Platform API](/docs/api-reference/platform-api.md) (OAuth, keys, settings) | `https://platform.api.thegrid.ai/v1` |
| [Trading API](/docs/api-reference/trading-api.md) (markets, orders)         | `https://trading.api.thegrid.ai/v1`  |

Anthropic Messages format: `https://messages-beta.api.thegrid.ai/v1` (same consumption key, `x-api-key` header).

## Step 1: Log in with the OAuth device flow

Request a device code ([RFC 8628](https://www.rfc-editor.org/rfc/rfc8628)):

```bash
curl -sS -X POST "https://platform.api.thegrid.ai/v1/oauth/device/code" \
  -H "Content-Type: application/json" \
  -d '{
    "client_id": "grid-cli-public",
    "scope": "account:read keys:manage"
  }'
```

The response includes `user_code`, `verification_uri` (typically `https://app.thegrid.ai/activate`), `device_code`, `expires_in`, and `interval` (seconds between polls).

Open `verification_uri`, sign in, and approve the requested scopes.

Poll for tokens. While the user has not yet approved, the endpoint returns `400` with a JSON body shaped `{ "error": "...", "error_description": "..." }`:

```bash
curl -sS -X POST "https://platform.api.thegrid.ai/v1/oauth/token" \
  -H "Content-Type: application/json" \
  -d '{
    "grant_type": "urn:ietf:params:oauth:grant-type:device_code",
    "client_id": "grid-cli-public",
    "device_code": "DEVICE_CODE_FROM_STEP_1"
  }'
```

A correct RFC 8628 client handles four polling errors, not just `authorization_pending`. Switch on the `error` field and react as follows:

| `error`                 | HTTP  | What it means                                         | What your client should do                                                                                |
| ----------------------- | ----- | ----------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |
| `authorization_pending` | `400` | User has not approved yet.                            | Keep polling. Wait `interval` seconds, then poll again.                                                   |
| `slow_down`             | `400` | You are polling too fast.                             | Increase your polling interval by **5 seconds** (`interval += 5`), then keep polling at the new interval. |
| `access_denied`         | `400` | User declined the request.                            | Stop polling. Surface the rejection; do not retry without a new device code.                              |
| `expired_token`         | `400` | The device code expired (see `expires_in`, \~15 min). | Stop polling. Start over from the device-code request in this step.                                       |

Any other `error` (for example `invalid_grant`) is terminal: stop polling and surface it. On success you get `200` with the token pair.

Save `access_token` (`grid_at_*`) and `refresh_token` (`grid_rt_*`). Access tokens expire in about one hour (`expires_in`, 3600). See [Refreshing tokens](#refreshing-tokens) below for the refresh request, token rotation, and timing.

### Refreshing tokens

Exchange a refresh token for a fresh pair at the same `/oauth/token` endpoint with `grant_type=refresh_token`:

```bash
curl -sS -X POST "https://platform.api.thegrid.ai/v1/oauth/token" \
  -H "Content-Type: application/json" \
  -d '{
    "grant_type": "refresh_token",
    "client_id": "grid-cli-public",
    "refresh_token": "grid_rt_…"
  }'
```

```json
{
  "access_token": "grid_at_…",
  "refresh_token": "grid_rt_…",
  "token_type": "Bearer",
  "expires_in": 3600,
  "scope": "account:read keys:manage"
}
```

Practical guidance for a robust client:

* **Treat refresh tokens as rotating.** A refresh response may return a new `refresh_token`; always persist whatever comes back (`tokens.refresh_token ?? existing`) and discard the old one.
* **Refresh ahead of expiry.** Refresh roughly **60 seconds before** the access token's `expires_in` elapses rather than waiting for a `401`, to absorb clock skew between your machine and the server.
* **Retry once on auth failure.** If an API call fails with `401`/`403` and an `invalid_token` error, refresh once and retry the call. If the refresh itself returns `400 invalid_grant`, the grant is gone — fall back to the full device flow in Step 1.

## Step 2: Create a consumption API key

Requires `keys:manage` on the access token.

```bash
export ACCESS_TOKEN="grid_at_…"

curl -sS -X POST "https://platform.api.thegrid.ai/v1/api-keys" \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"api_key": {"name": "my-agent"}}'
```

The response `data.key` is the consumption secret. Store it immediately. List and show endpoints return `key: null` afterward.

## Step 3: Make your first inference request

```bash
export CONSUMPTION_KEY="…"   # from data.key

curl -sS -L "https://api.thegrid.ai/v1/chat/completions" \
  -H "Authorization: Bearer $CONSUMPTION_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model": "text-prime", "messages": [{"role": "user", "content": "Hello"}]}'
```

Use `-L` with curl so the Consumption API `307` redirect is followed. See [Request routing and redirects](/docs/api-reference/request-routing-and-redirects.md).

That's it. Point your OpenAI-compatible client at `https://api.thegrid.ai/v1` with the consumption key and you are onboarded. See [General Agent Skill](/docs/integrations-and-best-practices/integrations/general-agent-skill.md) for client setup and 402 handling, and the guides under [Integrations](/docs/integrations-and-best-practices/integrations.md) for specific frameworks.

## Check setup without spending credits

Diagnostics endpoints are read-only. They verify auth and setup without placing orders, creating keys, switching modes, reserving tokens, or making billable inference calls.

If you use the Grid CLI:

```bash
grid diagnostics
```

If you are using raw HTTP, call the endpoint for the credential you want to verify:

```bash
# Platform OAuth / account setup
curl -sS "https://platform.api.thegrid.ai/v1/diagnostics" \
  -H "Authorization: Bearer $ACCESS_TOKEN"

# Consumption API key
curl -sS "https://api.thegrid.ai/v1/diagnostics" \
  -H "Authorization: Bearer $CONSUMPTION_KEY"

# Anthropic-style Consumption key header
curl -sS "https://api.thegrid.ai/v1/diagnostics" \
  -H "x-api-key: $CONSUMPTION_KEY"
```

Trading diagnostics uses the same Ed25519 signing scheme as the rest of the Trading API. See [Diagnostics](/docs/api-reference/diagnostics.md) for the signed request example and response codes.

## Optional: trading setup

Skip this section unless you want to read balances, list trades, or place orders yourself instead of letting [Auto Mode](/docs/start-here/auto-mode-vs-advanced-mode.md) buy on your behalf. You will need the `account:write` and `trade:*` scopes in Step 1 in addition to the ones above.

### Register a trading signing key

Generate an Ed25519 keypair locally (see [Authentication](/docs/api-reference/authentication.md#trading-keys)), then register the public key:

```bash
curl -sS -X POST "https://platform.api.thegrid.ai/v1/signing-keys" \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "signing_key": {
      "label": "my-bot",
      "public_key": "BASE64_RAW_32_BYTE_PUBLIC_KEY"
    }
  }'
```

Use the returned `fingerprint` as `x-thegrid-fingerprint` when signing Trading API requests. The private key never leaves your machine.

When signing, concatenate `{timestamp}{METHOD}{path}{body}`. Sign the **pathname only** (for example `/v1/orders`), not query parameters. A `GET /v1/orders?status=filled` request signs `/v1/orders` with an empty body; a `POST /v1/orders` signs `/v1/orders` plus the JSON body. See [Authentication](/docs/api-reference/authentication.md#sign-a-request).

### Enable trading on the account

Trading requires [Advanced Mode](/docs/start-here/auto-mode-vs-advanced-mode.md). Switch with `account:write`:

```bash
curl -sS -X POST "https://platform.api.thegrid.ai/v1/self/system-settings/account-mode" \
  -H "Authorization: Bearer $ACCESS_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"mode": "advanced"}'
```

Note that some account settings are read-only results of the account mode. The settings `GET` lists them in `mode_managed_fields`; writes that diverge from what the mode dictates return `403`. Details and all settings endpoints: [Platform API reference](/docs/api-reference/platform-api.md#account-settings).

If the account stays in Auto Mode, Trading API reads still work, but order create/update/cancel returns `403` with `auto_mode_trading_restricted` after onboarding.

### Start trading

Before placing an order:

1. `GET https://trading.api.thegrid.ai/v1/health` without auth to verify reachability.
2. Signed `GET /v1/me` to confirm credentials and `account_mode`.
3. Signed `GET /v1/trading-accounts` to inspect USD and per-instrument balances.
4. `GET /v1/markets` to read `order_controls` before choosing price and quantity.
5. Signed `GET /v1/account/limits?market_id=...` to read the order rate limit enforced for that market.

There is no bare `GET /v1/account` Trading endpoint. If you need identity or mode, call `/v1/me`; if you need order rate limits, call `/v1/account/limits?market_id=...`; if you need balances, call `/v1/trading-accounts` and `/v1/currency-trading-accounts`.

For limit orders, send `price` as a decimal string such as `"0.68"`, not the JSON number `0.68`. Numeric prices are rejected with `422`; keep quantities as whole integer lots and use the market's `tick_size`, `lot_size`, and `min_order_size` from `/v1/markets`.

From here the [Trading API](/docs/api-reference/trading-api.md) covers markets, balances, order placement, and transfers, authenticated with your signing key.

For filled Advanced Mode buys that should move straight into consumption, set `should_autotransfer: true` on supported Grid Exchange order requests. Sell orders still require available inventory in the instrument trading account.

## Where next

* [Consumption API](/docs/api-reference/consumption-api.md): inference endpoints and request shapes
* [Platform API](/docs/api-reference/platform-api.md): full OAuth, key, and settings reference
* [Authentication](/docs/api-reference/authentication.md): credential types and the signing scheme
* [Quickstart](/docs/start-here/quickstart.md): first inference call with a dashboard-created key
* [Auto Mode and Advanced Mode](/docs/start-here/auto-mode-vs-advanced-mode.md): what the account modes mean


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://thegrid.ai/docs/start-here/programmatic-onboarding.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
