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

# Exchange an API key for an access token

POST https://api-gateway.perkss.io/api/v1/auth/token
Content-Type: application/x-www-form-urlencoded

Start here. Exchanges your CMS-issued API credential (`client_id` + `perkss_sk_live_…` secret) for a short-lived Bearer token via the OAuth 2.0 client-credentials grant (RFC 6749 §4.4). Send the fields as an `application/x-www-form-urlencoded` body, or pass the credential pair via HTTP Basic authentication instead — the form fields win when both are present. `expires_in` in the response reflects the actually minted lifetime (`ttl_seconds` clamped to \[60, 86400]; default 86400 = 24h); cache the token and reuse it until then rather than exchanging per request. Every other `/api/v1` endpoint expects it as `Authorization: Bearer <access_token>`. Unlike every other endpoint, deliberate failures here use the RFC 6749 §5.2 error shape, not the standard error envelope.

Reference: https://docs.perkss.io/api-reference/perkss-partner-api/auth/api-token-exchange

## Authentication

- `Authorization` header (basic auth, required) — RFC 6749 client_secret_basic: API key id/secret as username/password — an alternative to the token-exchange form fields (the form wins when both are present). Only POST /api/v1/auth/token accepts it.

## Request

### Body (application/x-www-form-urlencoded)

This endpoint expects a TokenExchangeDto.

- `grant_type` (string, required) — OAuth 2.0 grant type — only client_credentials is supported.
- `client_id` (string, optional) — The API key id shown in the CMS key list.
- `client_secret` (string, optional) — The API key secret (perkss_sk_live_…) shown exactly once at creation. May alternatively be sent via HTTP Basic authentication.
- `ttl_seconds` (string, optional) — Requested token lifetime in seconds, clamped to [60, 86400]. Defaults to 86400 (24h). Use short TTLs for browser-bound tokens.

## Response

### 200

RFC 6749 §5.1 token response.

- `access_token` (string, required) — The Bearer token for all other /api/v1 endpoints. An opaque credential — do not parse or persist beyond its lifetime.
- `token_type` (enum, required)
  - Allowed values: `Bearer`
- `expires_in` (double, required) — Seconds until expiry — reflects the actually minted lifetime after the `ttl_seconds` clamp to [60, 86400].

## Errors

### 400 Bad Request Error

RFC 6749 §5.2 body: `invalid_request` (missing or malformed credentials) or `unsupported_grant_type` (anything but `client_credentials`).

- `error` (enum, required) — RFC 6749 §5.2 error code.
  - Allowed values: `invalid_request`, `invalid_client`, `unsupported_grant_type`
- `error_description` (string, optional) — Human-readable detail on what was wrong with the exchange.
- `request_id` (string, optional) — Extension member: correlates the failure with gateway logs — quote it when contacting support.

### 401 Unauthorized Error

RFC 6749 §5.2 body: `invalid_client` — unknown key id, wrong secret, or revoked key.

- `error` (enum, required) — RFC 6749 §5.2 error code.
  - Allowed values: `invalid_request`, `invalid_client`, `unsupported_grant_type`
- `error_description` (string, optional) — Human-readable detail on what was wrong with the exchange.
- `request_id` (string, optional) — Extension member: correlates the failure with gateway logs — quote it when contacting support.

### 429 Too Many Requests Error

`RATE_LIMIT.EXCEEDED` — token exchanges are throttled per IP (default 10/min). NOTE: unlike the RFC-shaped failures above, this response uses the standard error envelope.

- `error` (ErrorBody, required)

## Types

### ErrorBody

- `code` (string, required) — Machine-readable code, namespaced `<DOMAIN>.<NAME>`. Stable: branch on this, never on `message`.
- `message` (string, required) — Human-readable explanation. Not stable across releases — never branch on it.
- `requestId` (string, required) — Correlation id for this request — quote it when contacting support.
- `httpStatus` (double, required) — The response's HTTP status, mirrored into the body.
- `context` (map from string to any, optional) — Optional structured detail — e.g. `validation` messages on a 400, `failureReason` on a 422 rejected write.

## Examples

**Request**

```json
{
  "grant_type": "client_credentials"
}
```

**Response**

```json
{
  "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ…",
  "token_type": "Bearer",
  "expires_in": 86400
}
```

**SDK Code**

```python
import requests

url = "https://api-gateway.perkss.io/api/v1/auth/token"

payload = ""
headers = {
    "Content-Type": "application/x-www-form-urlencoded"
}

response = requests.post(url, data=payload, headers=headers, auth=("<username>", "<password>"))

print(response.json())
```

```javascript
const url = 'https://api-gateway.perkss.io/api/v1/auth/token';
const credentials = btoa("<username>:<password>");

const options = {
  method: 'POST',
  headers: {
    Authorization: `Basic ${credentials}`,
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  body: new URLSearchParams('')
};

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

```go
package main

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

func main() {

	url := "https://api-gateway.perkss.io/api/v1/auth/token"

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

	req.SetBasicAuth("<username>", "<password>")
	req.Header.Add("Content-Type", "application/x-www-form-urlencoded")

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

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

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

}
```

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

url = URI("https://api-gateway.perkss.io/api/v1/auth/token")

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

request = Net::HTTP::Post.new(url)
request.basic_auth("<username>", "<password>")
request["Content-Type"] = 'application/x-www-form-urlencoded'

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

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

HttpResponse<String> response = Unirest.post("https://api-gateway.perkss.io/api/v1/auth/token")
  .basicAuth("<username>", "<password>")
  .header("Content-Type", "application/x-www-form-urlencoded")
  .asString();
```

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

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api-gateway.perkss.io/api/v1/auth/token', [
  'form_params' => null,
  'headers' => [
    'Content-Type' => 'application/x-www-form-urlencoded',
  ],
    'auth' => ['<username>', '<password>'],
]);

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

```csharp
using RestSharp;
using RestSharp.Authenticators;

var client = new RestClient("https://api-gateway.perkss.io/api/v1/auth/token");
client.Authenticator = new HttpBasicAuthenticator("<username>", "<password>");
var request = new RestRequest(Method.POST);

request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
IRestResponse response = client.Execute(request);
```

```swift
import Foundation

let credentials = Data("<username>:<password>".utf8).base64EncodedString()

let headers = [
  "Authorization": "Basic \(credentials)",
  "Content-Type": "application/x-www-form-urlencoded"
]

let request = NSMutableURLRequest(url: NSURL(string: "https://api-gateway.perkss.io/api/v1/auth/token")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers

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()
```