# Build your own client

### Who this page is for

If you are building for iOS or macOS, use [AIProxySwift](https://github.com/lzell/AIProxySwift) — it handles everything on this page for you. This page documents the raw HTTP protocol for everyone else: a client in another language, another platform, or your own networking stack.

When you submit a provider key in the dashboard, we hand back two values:

- `serviceURL`, e.g. `https://api.aiproxy.com/4f865a6d/e88e2881`
- `partialKey`, e.g. `v2|1a2b3c4d|f3JQ…`

Copy them when they are shown — we don't store them, and the `partialKey` cannot be retrieved later.

### Making a request

Append the provider's path and query string to your `serviceURL` and send the request there, exactly as you would to the provider. AIProxy decrypts your provider key, attaches it in the header the provider expects, and streams the provider's response back to you unchanged — status code, headers, body, including server-sent events.

```
curl <serviceURL>/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "aiproxy-partial-key: v2|1a2b3c4d|f3JQ..." \
  -H "aiproxy-client-id: some-stable-id-for-this-user" \
  -d '{
    "model": "gpt-4o-mini",
    "messages": [{"role": "user", "content": "hello"}]
  }'
```

Do not attach the provider's own auth header (`Authorization`, `x-api-key`, and so on) — AIProxy adds it. Any other headers you send are forwarded to the provider as-is. If you omit `Content-Type` it defaults to `application/json`.

### Request headers

| Header | Description |
| --- | --- |
| `aiproxy-partial-key` | Required. The `partialKey` from the dashboard, sent verbatim. Requests without it are rejected with `400`. |
| `aiproxy-client-id` | Required. A stable identifier for the end user or install, chosen by you (an opaque UUID is a good choice; do not use personal data). It is how AIProxy attributes traffic: per-user rate limits, the Top Client Usage view, the request log, and client ID bans all key off this value. Requests without it are rejected with `403`. |
| `aiproxy-devicecheck` | Required when the service has DeviceCheck protection enabled; otherwise ignored. A base64 encoding of a fresh token from Apple's DeviceCheck framework (`DCDevice.current.generateToken()`). Tokens are single-use. |
| `aiproxy-devicecheck-bypass` | Development only. The bypass token from your app's DeviceCheck configuration, for environments that can't produce DeviceCheck tokens (e.g. the iOS simulator). Never ship it in a production client: anyone holding it can skip DeviceCheck. |
| `aiproxy-appattest-key-id` | Required when the service's verification method is App Attest; otherwise ignored. The base64 key ID returned by `DCAppAttestService.generateKey()`, registered once per install as described under [App Attest](#app-attest). |
| `aiproxy-appattest-assertion` | Required with App Attest. The base64 CBOR assertion from `DCAppAttestService.generateAssertion(_:clientDataHash:)` over this request's [client data hash](#app-attest-hash). |
| `aiproxy-appattest-nonce` | Required with App Attest. Base64 of 16 random bytes, fresh for every request. AIProxy rejects a nonce it has seen before for the same key. |
| `aiproxy-appattest-timestamp` | Required with App Attest. Unix seconds at signing time, as a decimal string. Rejected when more than 300 seconds from server time. |
| `aiproxy-appattest-bypass` | Development only. The bypass token from your app's App Attest configuration, for the iOS simulator, which has no Secure Enclave. Never ship it in a production client. |
| `aiproxy-key-format` | Optional, for providers we don't have a built-in auth rule for. See [custom providers](#custom-providers). |
| `aiproxy-metadata` | Optional telemetry, pipe-delimited: `v4|<bundle id>|<app version>|<sdk version>|<unix timestamp>|<os name>|<os version>|<device model>|<body size>`. In eproxy — relevant if you self-host — the fifth field (the request's unix timestamp, in seconds) drives the `client_to_proxy_latency` stat, and the whole string is written to the request logs of the utility endpoints (receipt validation, breadcrumbs, client-lib error reports). Omit it and those log fields read `unknown`; nothing is rejected. |
| `aiproxy-anonymous-id` | Optional. AIProxySwift sends a best-effort anonymous account UUID that stays stable across a user's iCloud devices (where `aiproxy-client-id` is per-install). eproxy currently strips it without consuming it — it is reserved for cross-device attribution, and self-hosted deployments are free to key their own logic off it. |

AIProxy strips the `aiproxy-*` headers before forwarding, so the provider never sees them.

### Request verification and non-Apple clients

Each service has one verification method, chosen in the dashboard: DeviceCheck, App Attest, or none. DeviceCheck tokens and App Attest assertions can only be produced by Apple hardware, so a client that isn't running on an Apple device cannot satisfy a protected service. If your custom client runs elsewhere, put it on a service with verification set to None, and lean on the other protections — rate limits, endpoint allowlists, and bans. Keep your Apple traffic on a separate, protected service; services are free to create within an app.

DeviceCheck needs one header per request, `aiproxy-devicecheck`, carrying a fresh token from `DCDevice.current.generateToken()`. App Attest is stronger (the assertion binds the request contents to a Secure Enclave key attested for your bundle ID) and costs no per-request round trip to Apple, but it takes a one-time registration. The rest of this section is the App Attest contract.

### App Attest

An App Attest client does three things: generate a key in the Secure Enclave and register it with AIProxy once per install, sign every request with that key, and start over with a new key if AIProxy reports the key as unknown. A key belongs to the app, not to a service: registration happens at the app's own route, and the key then verifies on every service in the app, so an app with several App Attest services registers once. Both App Attest environments (development builds from Xcode and production builds) are accepted; the environment a key came from is recorded with it.

#### Registration, once per install

1. Call `DCAppAttestService.shared.generateKey()` and keep the returned key ID. If `isSupported` is false (the simulator, or hardware without a Secure Enclave), use the bypass token instead.
2. Ask AIProxy for a challenge:
```
# The app's route: the service URL with its last segment removed.
curl https://api.aiproxy.com/<app>/aiproxy/v1/attest/challenge \
  -H "Content-Type: application/json" \
  -H "aiproxy-client-id: some-stable-id-for-this-user" \
  -d '{"key_id": "<key id>"}'

{ "challenge": "<base64, 32 bytes>", "expires_in": 300 }
```
3. Attest the key with Apple: `attestKey(keyID, clientDataHash: SHA256(challenge bytes))`. The hash is over the decoded challenge, not the base64 text.
4. Register the attestation within the 300-second window:
```
curl https://api.aiproxy.com/<app>/aiproxy/v1/attest/register \
  -H "Content-Type: application/json" \
  -H "aiproxy-client-id: some-stable-id-for-this-user" \
  -d '{"key_id": "<key id>", "attestation_object": "<base64 attestation>"}'
```
 A `204` means the key is registered. Persist the key ID on the device (the Keychain, device-only) and reuse it for the life of the install.

A third route, `POST …/aiproxy/v1/attest/verify`, takes a signed request and reports whether it verified, so you can test registration and signing together before touching a provider; see [Testing App Attest end to end](/docs/testing-app-attest.html).

The attestation routes live at the app level, `https://api.aiproxy.com/<app>/aiproxy/v1/attest/…`, where `<app>` is the first path segment of any of your service URLs. They take no `aiproxy-partial-key` and require `aiproxy-client-id`. They carry a fixed limit of 30 challenges per client ID and 300 per IP address per hour, since a legitimate install registers once; a `429` means a client is looping. A `409` from register means the key ID already exists: generate a new key rather than re-registering the old one. Because Apple rate limits attestation too, back off after a failed registration instead of retrying in a loop; honor `Retry-After` on a `429`.

#### Signing each request

Generate a nonce and a timestamp, compute the client data hash below, and pass it to `generateAssertion(keyID, clientDataHash:)`. Send the four `aiproxy-appattest-*` headers alongside the usual `aiproxy-partial-key` and `aiproxy-client-id`. AIProxy recomputes the hash from the request it received and verifies the assertion against the registered public key, so the values must match byte for byte.

```
client_data_hash = SHA256(
    "aiproxy-appattest-v1" + "\n" +
    method + "\n" + # e.g. POST
    path + "\n" + # percent-encoded, no query string
    SHA256(body) + "\n" + # the raw 32-byte digest, not hex; SHA256("") for an empty body
    nonce + "\n" + # the base64 text sent in aiproxy-appattest-nonce
    timestamp + "\n" + # decimal unix seconds, as sent
    key_id # the base64 key ID, as sent
)
```

- `path` is the full request path as sent to AIProxy, including the app and service segments: `/4f865a6d/e88e2881/v1/chat/completions`. Query strings are never part of the hash.
- `body` is the exact bytes on the wire. Sign after the body is final, and never re-serialize between signing and sending.
- A nonce is single-use per key. A retry must be signed again with a fresh nonce and timestamp.
- The device clock must be within 300 seconds of AIProxy's.

#### Errors specific to App Attest

All are `403` with `error.type` set as below (see [Responses and errors](#responses-and-errors)).

| `error.type` | Meaning | What the client should do |
| --- | --- | --- |
| `app_attest_missing` | The service requires App Attest and one or more `aiproxy-appattest-*` headers are absent. | Register and sign, or send the bypass token in development. |
| `app_attest_unknown_key` | The key ID is not registered for this app. | Discard the stored key ID, generate a new key, and register again. Do not retry with the same key. |
| `app_attest_failed` | The assertion did not verify against the registered key. Almost always a hash mismatch: wrong path, a body that changed after signing, or a nonce, timestamp, or key ID that differs from the header. | Fix the hash inputs. The message names the check that failed. |
| `app_attest_replay` | This nonce was already used with this key. | Sign again with a fresh nonce. |
| `app_attest_stale` | The timestamp is more than 300 seconds from server time. | Check the device clock; sign again. |
| `app_attest_malformed` | The timestamp is not decimal unix seconds. | Fix the header. |
| `app_attest_challenge_missing` | Register was called with no pending challenge, or after the 300-second window. | Request a new challenge and attest again. |
| `app_attest_registration_failed` | The attestation did not verify, most often because it is for a different team ID or bundle ID than the app's App Attest configuration. | Check the App Attest tab in the dashboard against the app's entitlements. |
| `app_attest_key_already_registered` | Register was called for a key ID that already exists (`409`). | Generate a new key. |
| `incorrect_app_attest_bypass` | The bypass token does not match the app's. | Check the App Attest tab in the dashboard. |
| `incorrect_app_attest_configuration` | The service requires App Attest but the app has no team ID and bundle ID configured. | Fill in the App Attest tab in the dashboard. |

### Responses and errors

When a request reaches the provider, you get the provider's response verbatim — including provider error statuses. When AIProxy itself rejects the request, the status is one of the codes below and the body is JSON:

```
{ "error": { "type": "no_client_id_header", "message": "AIProxy requires a client ID header" } }
```

`error.type` is a stable identifier for the rejection, meant for code to branch on; `error.message` is prose for people and may change. Branch on the type, not the message.

| Status | Rejected because |
| --- | --- |
| `400` | The request is malformed: the `aiproxy-partial-key` header is missing or does not match the expected `v2|…|…` shape, or the URL path is missing the app and service segments. |
| `403` | The `aiproxy-client-id` header is missing; the path is not in the service's endpoint allowlist; the partial key does not decrypt a key on the service (deleted or mistyped); DeviceCheck failed or the bypass token is wrong; the App Attest assertion is missing or did not verify (see the [App Attest error types](#app-attest)); or the client ID / IP address is banned. `error.type` says which. |
| `404` | The app or service segment of the URL does not exist (check your `serviceURL`). |
| `429` | A rate limit you configured in the dashboard was hit. |

### Custom providers

For the providers listed in the dashboard, AIProxy already knows which header carries the key (e.g. `Authorization: Bearer …` for OpenAI, `x-api-key` for Anthropic, `x-goog-api-key` for Gemini). For any other domain the default is `Authorization: Bearer <key>`.

If your provider expects something else, send `aiproxy-key-format` with the header name and a template containing ``, separated by a colon:

```
aiproxy-key-format: x-custom-auth:Token
```

That example makes AIProxy attach `x-custom-auth: Token <your provider key>` upstream.

### WebSocket and gRPC

WebSocket proxying (e.g. the OpenAI Realtime API) and gRPC use the same identifiers on a different handshake. Both are verified once, when the connection is established, with the same headers as above:

- WebSocket. Send `aiproxy-partial-key`, `aiproxy-client-id`, and the verification headers on the HTTP upgrade request to `<serviceURL>/v1/realtime?model=…`. For App Attest, the signed method is `GET`, the signed path is the upgrade path without its query string (`/<app>/<service>/v1/realtime`), and the signed body is empty. A failed check closes the socket.
- gRPC. The RPC path leaves no room for the app and service segments, so the identifiers travel as request metadata: `aiproxy-project`, `aiproxy-service`, `aiproxy-partial-key`, `aiproxy-client-id`, and the verification headers under their usual names. For App Attest, the signed method is `POST`, the signed path is the gRPC `:path` exactly as sent (`/package.Service/Method`), and the signed body is empty, because the call is authorized before the request body streams. Failures come back as trailers-only responses with status `UNAUTHENTICATED` and the same messages as the HTTP path.

The complete client behavior for both is implemented in [AIProxySwift](https://github.com/lzell/AIProxySwift). If anything on this page is unclear, let us know at [support@aiproxy.com](mailto:support@aiproxy.com).


