# Using the API

## Overview

The Aiwyn API lets your firm's software work with your Aiwyn data directly, without anyone needing to click through the Firm Portal. An automation uses it to look up the details it needs, such as a client, an engagement, or a document's status, and to create or update records, such as an expense or a contact.

The essentials:

- **Access is by API key.** Aiwyn issues your firm a key. It works like a password for software, and its roles decide which APIs it can call.
- **Test in the sandbox first.** The sandbox is a separate copy of Aiwyn for building and testing. Each environment has its own keys: a sandbox key does not work in production, and the reverse.
- **Request the roles for the APIs you call.** Every key has the base `API_ADMIN` role, which covers every read under `/gql/v1/` and some `/api/v1/` endpoints. Other `/api/v1/` endpoints, including most writes, need their own role, which the API reference lists on each endpoint.
- **Every endpoint is documented** in the [API reference](/bundle). This guide explains how the pieces fit; the reference has every field.


From here, the guide gets more technical and is written for the developer building the automation.

## Getting access

1. **Decide the roles.** The API reference lists the role each endpoint requires, and [Authorization](/reference/authorization) describes the roles. A consent-status automation reads engagements and their documents under `/gql/v1/`, which the base role covers, so it only needs `EVNT_SUB` to subscribe to the event. An expense automation needs `TM_ENTRY_C` to write time and expense entries, and `TM_CODE_R` if it looks up expense codes.
2. **Request a sandbox key** from your Aiwyn contact with those roles. Keys are sent only to an authorized email at your firm.
3. **Build and test against the sandbox.**
4. **Request a production key** with the same roles when you are ready to go live.


| Environment | Base URL | Use it for |
|  --- | --- | --- |
| Sandbox | `https://api.sandbox.aiwyn.app` | Building and testing against test data |
| Staging | `https://api.staging.aiwyn.app` | Final checks before you go live, on a production-like setup |
| Production | `https://api.aiwyn.ai` | Your firm's live data |


Sandbox and Staging sit behind Cloudflare Access. Every request to them, including the token exchange, must also send the `CF-Access-Client-Id` and `CF-Access-Client-Secret` headers that Aiwyn issues you. Production does not use them. See [Base URLs](/reference/base-urls#cloudflare-access-sandbox-and-staging).

Please treat a key like a password: keep it in a secrets manager or your platform's encrypted settings, and out of code and shared documents. If you think a key may have been exposed, ask Aiwyn to rotate it and you'll get a new one.

## Authenticating and making a first call

Your automation swaps its API key for a short-lived token, then sends that token with every request. The examples use `$AIWYN_BASE_URL` for the environment's base URL; on Sandbox and Staging, add the two Cloudflare Access headers to each one.

**1. Exchange the key for a token.**

```bash
curl --request POST "$AIWYN_BASE_URL/v1/auth/token" \
  --header 'Content-Type: application/json' \
  --data '{ "jwtApiKey": "<your-api-key>" }'
```

The response holds a `token`. It lasts up to an hour, and the exchange can return a token it issued earlier, so a token you have just received may have only minutes left.

**2. Send the token on each request.**

```bash
curl --request GET "$AIWYN_BASE_URL/gql/v1/engagement/34567" \
  --header 'Authorization: Bearer <token>'
```

**3. Handle expiry.** Cache the token and reuse it. When a request returns `401 Unauthorized`, get a new token and retry that request once. Requesting a new token for every call is slower and adds load you don't need.

A `403 Forbidden` is different: the token is valid, but the key lacks the role for that endpoint. A retry will not fix it; ask for the role to be added.

See [Authentication](/reference/authentication) for the details, or the [Quickstart](/reference/quickstart) for the whole flow in one place.

## Reading data

Most record types can be read in three ways. It's usually best to pick the narrowest one that answers your question.

| Way | Use it when | Example |
|  --- | --- | --- |
| Get by ID | You already have the Aiwyn ID, usually from a webhook payload | `GET /gql/v1/engagement/34567` |
| Search | You know something about the record but not its ID | Find the client whose `pmsRef` is `C-1042`, or every project updated since yesterday |
| List | You need every record of a type, such as for a first full sync | `POST /gql/v1/clients` |


Reads live under `/gql/v1/`. A response is keyed by the resource name, and a get by ID that finds nothing returns `200` with an empty result rather than `404`, so check for it.

Search takes a `where` filter built from field conditions, combined with `_and` and `_or`. For example, to find clients by name or reference:

```json
{
  "pageSize": 50,
  "page": 0,
  "where": {
    "_or": [
      { "name": { "_ilike": "%tech%" } },
      { "clientRef": { "_ilike": "%45%" } }
    ]
  }
}
```

List takes only `pageSize` and `page`. To fetch only what changed, search with a condition on `updatedAt`, such as `{ "updatedAt": { "_gt": "2026-11-01T00:00:00Z" } }`.

Some records have related lookups. An engagement's documents, for example, come from their own endpoint, which returns each document's type and consent outcome. Check the reference for the record you need.

## Writing data

Writing to Aiwyn comes in two styles.

**Single-record actions** do one thing to one record: onboard a client, create an engagement, or assign staff to a project. Each returns the result or an error for that one record.

**Create-or-update (upsert) endpoints** take a batch of up to 100 records. Time and expense entries (`POST /api/v1/entries`), work and expense codes (`POST /api/v1/codes`), and records such as clients, projects, and custom records (`POST /api/v1/records`) all work this way. Give each record a `systemRef`, your own reference for it:

```json
{
  "records": [
    {
      "type": "ExpenseEntry",
      "systemRef": { "system": "VENDOR", "reference": "charge-88213" },
      "attributes": { "...": "..." }
    }
  ]
}
```

If a record with that `systemRef` already exists, Aiwyn updates it; if not, Aiwyn creates it. That makes upserts **safe to retry**: send the same record twice and you still have one record. Use a stable ID from the other system as the `reference`, never a timestamp or a random value. A record sent to `/api/v1/records` without a `systemRef` is created again on every call. Entries and codes without a `systemRef` fall back to matching on `attributes.pmsRef`, and a `systemRef` that matches nothing falls back to an entry or code whose `pmsRef` equals its `reference`.

Contacts have their own upsert, `POST /api/v1/contacts/upsert`, which matches on the contact's `pmsRef` and returns the saved and failed contacts as two lists.

The response reports each record separately. For time and expense entries and codes, the status code tells you the overall result:

| Status code | Meaning |
|  --- | --- |
| `200` | Every record was saved |
| `207` | Some records were saved, and some failed |
| `422` | Every record failed |


`POST /api/v1/records` returns `200` even when records fail, so read the per-record results there too. Each record has a status, such as `INSERTED`, `UPDATED`, or `FAILED`, and a failed record carries an error code. An entry fails with `INACTIVE_CLIENT`, `INACTIVE_PROJECT`, or `LOCKED`, for example. Always read the per-record results; a `207` is not a success. See [Batch writes: per-record results](/reference/errors#batch-writes-per-record-results).

Two things worth knowing before you write entries:

- **Entries arrive approved and posted** unless you send `"approved": false` and `"posted": false`. Send `false` if someone at the firm should review them before billing.
- **Entries already on an invoice are locked.** Updating one fails with `LOCKED`.


The schema endpoint for each entry or code type (for example `GET /api/v1/entries/schema/ExpenseEntry`) returns the exact fields your firm's Aiwyn accepts, including custom fields. Call it while building.

## Errors, paging, and rate limits

**Errors** come back as a standard HTTP status with a JSON body. The body's shape depends on the endpoint family, and [Errors](/reference/errors) shows each one; branch on the status code first.

| Status | What to do |
|  --- | --- |
| `400` | Fix the request; retrying the same request will fail again |
| `401` | Get a new token, then retry once |
| `403` | Ask for the missing role; do not retry |
| `404` | The resource does not exist in this environment; check you are not mixing sandbox and production IDs |
| `429` | You are sending too fast; wait and retry with increasing delays |
| `500` | Retry with increasing delays; if it persists, contact Aiwyn |


**Paging** on `/gql/v1/` list and search endpoints uses `pageSize` (how many records, up to 1,000) and `page`. There, `page` is the number of records to skip, not a page number: for the second block of 1,000, send `page: 1000`, not `page: 1`. Each response includes `total.aggregate.count`; stop when `page` reaches it. A few `/api/v1/` endpoints page by page number instead; [Pagination](/reference/pagination) lists them.

**Rate limits** protect the service. Over the limit, the API returns `429`. Wait and retry with an increasing delay plus a little randomness. Fetch in large pages rather than many small calls. If your automation needs a higher sustained rate, contact [api-support@aiwyn.ai](mailto:api-support@aiwyn.ai). See [Rate limits](/reference/rate-limits).

## Related guides

- [Building automations](/guides/building-automations): the overview, and what your firm owns.
- [Tracing IDs](/guides/ids-and-tracing): which IDs to store and how records connect.
- [Using the webhooks](/guides/webhooks): getting told when something happens instead of polling for it.
- [API reference](/bundle): every endpoint, role, field, and response.