# Exchange a grant for an access token

Supports the authorization_code, refresh_token, device code (RFC 8628), auth.md claim and ID-JAG (urn:ietf:params:oauth:grant-type:jwt-bearer) grants; the...

`POST /api/v1/auth/oauth2/token`

- Sign-in: None at the router: the operation is public, or checks its own proof (a signature, a token in the body, a signed link).
- Rate limit: Up to 500 requests every 3 seconds per IP address; up to 1,000 requests a minute per API key (some requests are not counted); up to 300 requests a minute per IP address; up to 150 requests a minute per oauthClientLimiterKey.

Supports the `authorization_code`, `refresh_token`, device code (RFC 8628), auth.md claim and ID-JAG (`urn:ietf:params:oauth:grant-type:jwt-bearer`) grants; the access token is minted by the app's own server, and a failure there answers 503 `temporarily_unavailable`. Clients authenticate with `client_id` and `client_secret` in the body or with HTTP Basic, public clients by `client_id` plus PKCE; refresh of a non-agent client's token needs no client authentication. Errors use the RFC 6749 error shape, and every answer carries `Cache-Control: no-store`.

## Request

Send the body as `application/json` or `application/x-www-form-urlencoded`. The body is optional.

| Field           | Type                                                         | Required | Constraints             | Description |
| --------------- | ------------------------------------------------------------ | -------- | ----------------------- | ----------- |
| `grant_type`    | string or number or boolean or null                          | No       | at most 4096 characters | -           |
| `code`          | string or number or boolean or null                          | No       | at most 4096 characters | -           |
| `redirect_uri`  | string or number or boolean or null                          | No       | at most 4096 characters | -           |
| `code_verifier` | string or number or boolean or null                          | No       | at most 4096 characters | -           |
| `refresh_token` | string or number or boolean or null                          | No       | at most 4096 characters | -           |
| `device_code`   | string or number or boolean or null                          | No       | at most 4096 characters | -           |
| `claim_token`   | string or number or boolean or null                          | No       | at most 4096 characters | -           |
| `client_id`     | string or number or boolean or null                          | No       | at most 4096 characters | -           |
| `client_secret` | string or number or boolean or null                          | No       | at most 4096 characters | -           |
| `resource`      | one of: string or number or boolean or null, array of string | No       | -                       | -           |

## Example request

Replace each `YOUR_...` value with your own.

```bash title="cURL"
curl -X POST "https://api.console.buildbase.app/api/v1/auth/oauth2/token" \
  -H "Content-Type: application/json" \
  -d '{
  "grant_type": "string",
  "code": "string",
  "redirect_uri": "https://example.com"
}'
```

```ts title="TypeScript"
const response = await fetch(
  'https://api.console.buildbase.app/api/v1/auth/oauth2/token',
  {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      grant_type: 'string',
      code: 'string',
      redirect_uri: 'https://example.com',
    }),
  }
);
if (!response.ok) {
  throw new Error(`${response.status}: ${await response.text()}`);
}
const data = await response.json();
```

```python title="Python"
import requests

response = requests.post(
    "https://api.console.buildbase.app/api/v1/auth/oauth2/token",
    json={
        "grant_type": "string",
        "code": "string",
        "redirect_uri": "https://example.com",
    },
    timeout=30,
)
response.raise_for_status()
data = response.json()
```

## Responses

### 200 OK

OK

```json title="Example"
{
  "access_token": "[REDACTED]",
  "email": "user@example.com",
  "expires_in": 900,
  "name": "Session User authtime-priya",
  "refresh_token": "[REDACTED]",
  "scope": "files:read",
  "token_type": "[REDACTED]"
}
```

### Any other status

Any other answer the handler sends itself (its own refusals). Not described yet.

## Errors

Each refusal, what it means, and what to do. The request changed nothing.

### 400 Bad Request

**What it means:** The request was refused in the OAuth 2.0 error shape (RFC 6749 section 5.2): `error` is a code such as `invalid_request`, `invalid_grant`, `unsupported_grant_type` or `invalid_scope`, and `error_description` says why in words. Branch on `error`, never on the description.

**What to do:** Fix the field the body names in `path` (or read `message`) and send the request again. Nothing was changed.

```json title="Example"
{
  "error": "string",
  "error_description": "string"
}
```

### 401 Unauthorized

**What it means:** Client authentication failed (RFC 6749 section 5.2): `error` is `invalid_client`. When the client sent its credentials with HTTP Basic, the answer carries a `WWW-Authenticate` header.

**What to do:** Send the credential this operation asks for (see Sign-in above), or sign in again if it expired. A valid credential is also refused when the role has no grant for the permission above.

```json title="Example"
{
  "error": "string",
  "error_description": "string"
}
```

### 429 Too Many Requests

**What it means:** A rate limit in `x-rateLimit` was reached. `retryAfter` and the `Retry-After` header say how many seconds until the window resets.

**What to do:** Wait the number of seconds in the `Retry-After` header (also `retryAfter` in the body), then retry. Slow down repeated calls.

```json title="Example"
{
  "success": false,
  "message": "string",
  "reason": "rate_limited",
  "retryAfter": 1
}
```

## Related

- [OAuth 2.0 guide](/authentication/overview): how this part of BuildBase works
- [All OAuth 2.0 operations](/http-api/reference/oauth-2-0)
- [API reference](/http-api/reference): every operation, by tag
- [Sign-in and credentials for the HTTP API](/http-api/authentication)
- [How the HTTP API reports errors](/http-api/errors)
- [Make your first call](/http-api/first-call)
- [Error codes](/reference/error-codes): every `code` the API returns
- OpenAPI: operation `oauth2.token.create` in [public-v1.json](https://docs.buildbase.app/openapi/public-v1.json)
