# Call the API

> Sign a script in as a realm administrator, find the address of every product's API on your realm's host, and follow the paging, revisions and errors every call shares.

Everything the dashboard does, it does through your realm's APIs, and a script can make the same calls. Some
settings are set through the API alone, and their pages show the call. This page is what every one of those pages
assumes: where each API lives, how to get the session the calls carry, and the rules every call follows.

Every call on this site is written on your realm's own host, `https://foobar.cvyuh.com`, where `foobar` stands for
your realm. Put your realm's host in its place.

## Before you begin

- **An account with the rights the calls need.** A user in a group that holds a privilege in the realm: `RealmOwner`
  to change anything, `RealmViewer` to read, or a role of your own. See
  [Delegated administration](/platform/realms/delegated-administration/).
- **A sign-in chain a script can answer**: a name, a password, and if you like a code from an authenticator app.
- **`curl`**, and `jq` to script the calls.

## Where each API lives

| Product | Base |
|---|---|
| Directory, sign-in settings, policies, agents, keys, sessions, privileges | `https://foobar.cvyuh.com/api/v0/am` |
| Realms (create and manage sub-realms) | `https://foobar.cvyuh.com/api/v0/am/global/realms/v1` |
| Secrets Store, managed vaults | `https://foobar.cvyuh.com/api/v0/vault/managed/v1` |
| Secrets Store, sealed vaults | `https://foobar.cvyuh.com/api/v0/vault/sealed/v1` |
| Endpoint Management: devices | `https://foobar.cvyuh.com/api/v0/endpoint/ppm/v1` |
| Detection & Response: security log, response | `https://foobar.cvyuh.com/api/v0/endpoint/dar/v1` |
| AI Governance: the AI fleet | `https://foobar.cvyuh.com/api/v0/endpoint/aig/v1/api/v1` |
| Apps and agents: OAuth 2.0, OpenID Connect | `https://foobar.cvyuh.com/oauth2/…` |
| Gateway and enforcement points: policies, decisions | `https://foobar.cvyuh.com/policies/v1`, `https://foobar.cvyuh.com/access/v1` |

The administration APIs (every row but the last two) take a realm administrator's **session**. The last two are
called by apps, agents and enforcement points with credentials of their own, as their standards say: see
[Apps and agents](../apps-and-agents/).

Each product's **API reference** lists every endpoint it serves, by area: each is listed in
[Develop](../).

## Get a session

The administration APIs take one credential: a session, the same kind the dashboard holds after you sign in. A
script gets one by signing in the way the dashboard does, as a user who holds a realm administrator's rights, and
sends it as a cookie on every call. Every page on this site writes it as `$CVYUH_SESSION`.

<Steps>

1. **Start a sign-in.** Post an empty body. The realm runs its default sign-in chain and answers with the first page
   of prompts, and an `authId` that names this sign-in:

   ```sh
   curl -X POST https://foobar.cvyuh.com/api/v0/am/auth/v1/authenticate \
     -H "Content-Type: application/json" \
     -d '{}'
   ```

   ```json
   {
     "authId": "<auth id>",
     "header": "Sign in",
     "prompts": [
       { "kind": "name", "output": [{ "name": "prompt", "value": "User name" }], "input": [{ "value": "" }] },
       { "kind": "password", "output": [{ "name": "prompt", "value": "Password" }], "input": [{ "value": "" }] }
     ]
   }
   ```

2. **Answer the prompts.** Send the `authId` back, with each prompt's `kind` and your answer in its `input`:

   ```sh
   curl -X POST https://foobar.cvyuh.com/api/v0/am/auth/v1/authenticate \
     -H "Content-Type: application/json" \
     -d '{
       "authId": "<auth id>",
       "prompts": [
         { "kind": "name", "input": [{ "value": "maya" }] },
         { "kind": "password", "input": [{ "value": "<password>" }] }
       ]
     }'
   ```

   If the chain has another step, such as a code from an authenticator app (`kind` `code`), the answer is the next
   page with a new `authId`: answer it the same way. When the chain is done, the answer carries the session as
   `tokenId`:

   ```json
   { "tokenId": "<session>", "successUrl": "<url>" }
   ```

3. **Keep the session in `CVYUH_SESSION`.**

   ```sh
   export CVYUH_SESSION="<session>"
   ```

4. **Check it works.** `whoami` answers who you are, your roles in the realm, and how long the session has left
   (`session.expiresInSecs`):

   ```sh
   curl -X POST https://foobar.cvyuh.com/api/v0/am/whoami/v1 \
     -H "Cookie: x-cvyuh-token=$CVYUH_SESSION"
   ```

</Steps>

A wrong password answers `401` with the code `INVALID_CREDENTIALS`; a sign-in left too long between steps answers
`408` with `LOGIN_TIMEOUT`, and you start again from step 1.

In a script, with `jq`, the two steps of a name-and-password chain are:

```sh
AUTH_ID=$(curl -s -X POST https://foobar.cvyuh.com/api/v0/am/auth/v1/authenticate \
  -H "Content-Type: application/json" -d '{}' | jq -r .authId)

export CVYUH_SESSION=$(curl -s -X POST https://foobar.cvyuh.com/api/v0/am/auth/v1/authenticate \
  -H "Content-Type: application/json" \
  -d "{\"authId\":\"$AUTH_ID\",\"prompts\":[
        {\"kind\":\"name\",\"input\":[{\"value\":\"maya\"}]},
        {\"kind\":\"password\",\"input\":[{\"value\":\"$PASSWORD\"}]}]}" | jq -r .tokenId)
```

To end the session:

```sh
curl -X POST https://foobar.cvyuh.com/api/v0/am/auth/v1/logout \
  -H "Cookie: x-cvyuh-token=$CVYUH_SESSION"
```

<Aside type="note" title="The cookie's name">
  The session cookie is `x-cvyuh-token`. The server's public settings name it, and need no credential:
  `curl https://foobar.cvyuh.com/api/v0/am/global/serverinfo/v1` answers it as `cookieName`.
</Aside>

### Sessions in scripts

A script's session is the same thing as the dashboard's. It carries the rights of the account it signed in with,
decided by [Delegated administration](../../platform/realms/delegated-administration/), and follows the realm's
[Sessions](../../workforce-identity/authentication/sessions/) settings: it ends after
`maxSessionMinutes` (120 by default) or after `maxIdleMinutes` unused (30 by default), and wrong passwords count
toward a lockout. The dashboard keeps its session in a cookie the page's own scripts can't read, so a script signs in
on its own rather than borrowing it.

Plan a script around three facts:

- **Sign in once per run, and reuse the session.** One user holds at most `sessionQuota` sessions (10 by default),
  and a sign-in past that ends the user's oldest. A script that signs in on every call ends its own earlier
  sessions, and the dashboard's. End the session with `logout` when the run is done.
- **Give scripts their own account.** A user of their own, in a group with only the rights the script needs, keeps
  its sessions apart from a person's and its actions apart on the audit trail.
- **Use a chain a script can answer.** A script can answer a name, a password and an authenticator-app code. It
  can't use a passkey, so the script's account must have none.

### Protect a script's account

A script's account can do whatever its group may, for as long as its session lasts, and the admin APIs don't take an
app's own credentials yet. Treat its password as you would an administrator's:

- **Give it the least it needs.** Put the account in a group of its own, and grant that group `RealmViewer` if the
  script only reads, or a [role of your own](/platform/realms/delegated-administration/#roles-of-your-own) that covers
  only what it changes. Never `RealmOwner` for a script that doesn't need it.
- **Keep its password in a secret store,** such as a vault in the [Secrets Store](/secrets-store/) or your CI
  system's secrets, and read it into the script at run time. Never in the script, a repository or a command line.
- **Add an authenticator-app code.** Register an authenticator for the account, keep its secret in the same store,
  and have the script compute each code (for example with `oathtool --totp -b "$TOTP_SECRET"`). A stolen password alone
  then gets nowhere.
- **Keep its sessions short.** A script's session follows the realm's [Sessions](../../workforce-identity/authentication/sessions/)
  settings: sign in at the start of a run and sign out at the end.
- **Watch it.** The account's sign-ins and its changes are on the audit trail under its own name: see
  [Read a user's or agent's trail](/audit-reports/audit-trail/read-a-trail/).

Wrong passwords count toward the account's lockout like anyone's, so a script with a stale password locks its own
account out. Fix the password before running it again.

<Aside type="note" title="Writes from a browser page">
  A script that sends no `Origin` header is not a browser and may write with the cookie. A page on another site that
  calls the API from a browser must be listed in the realm's `corsSettings` first: see
  [Allowed origins](/platform/cross-origin/allowed-origins/).
</Aside>

## Conventions

### Objects and settings

Under `https://foobar.cvyuh.com/api/v0/am`, every setting and object is read and written the same way. Each has a
**type**, and each object an id:

| Call | What it does |
|---|---|
| `GET /api/v0/am/objects/v1/<type>` | List the objects of a type, one page at a time |
| `POST /api/v0/am/objects/v1/<type>?id=<id>` | Create one; leave out `id` and the realm picks one |
| `GET /api/v0/am/objects/v1/<type>/<id>` | Read one |
| `PUT /api/v0/am/objects/v1/<type>/<id>` | Replace it whole |
| `PATCH /api/v0/am/objects/v1/<type>/<id>` | Change only the fields you send |
| `DELETE /api/v0/am/objects/v1/<type>/<id>` | Delete it |
| `GET /api/v0/am/objects/v1/<type>/<id>/history` | Its changes, newest first |
| `GET /api/v0/am/types/v1` | The realm's types and their schemas |

Reading the user `maya`:

```sh
curl https://foobar.cvyuh.com/api/v0/am/objects/v1/user/maya \
  -H "Cookie: x-cvyuh-token=$CVYUH_SESSION"
```

A realm setting such as `sessionSettings` is a type with one object, whose id is the type's name:
`https://foobar.cvyuh.com/api/v0/am/objects/v1/sessionSettings/sessionSettings`. A setting you never set takes its
default, and a read shows every setting with its default filled in.

### Paging and filters

A list answers one page: `data`, with `page`, `pageSize`, `totalCount` and `totalPages`.

- **`page`** counts from 1. **`pageSize`** is 20 by default and 100 at most.
- **`filter`** is a JSON search document: `text` for a free-text match, and `filter` for a tree of conditions, such
  as `{"filter":{"field":"status","op":"=","value":"inactive"}}`. Encode it for a URL. See
  [Search and paging](../../directory/users/search/) for the full grammar.
- **`sort`** names a field, with `-` before it for descending: `?sort=-createTime`.
- **`totalPolicy=none`** skips the count, for a faster answer on a large list.
- **`cursor`** pages by a continuation instead: the answer carries `hasMore` and `nextCursor`, and you send
  `nextCursor` back as `cursor` for the next page.
- **`expand`** names the links to include: `?expand=memberOf` for a user's group links, `?expand=memberOf/*` for the
  groups themselves.

```sh
curl "https://foobar.cvyuh.com/api/v0/am/objects/v1/user?pageSize=50&sort=-createTime&expand=memberOf" \
  -H "Cookie: x-cvyuh-token=$CVYUH_SESSION"
```

Where a filter is too long for an address, send the same request with the method `QUERY` and the parameters as a
JSON body. The security log's lists are `POST`s that take the same `page`, `pageSize`, `sort` and filter in the body.

### Revisions and `If-Match`

Every object carries a revision, `rev`, in its body and as its `ETag`. Send it back in `If-Match`, and the write
applies only if no one has changed the object since you read it:

```sh
curl -X PATCH https://foobar.cvyuh.com/api/v0/am/objects/v1/sessionSettings/sessionSettings \
  -H "Cookie: x-cvyuh-token=$CVYUH_SESSION" \
  -H 'If-Match: "<rev>"' \
  -H "Content-Type: application/json" \
  -d '{ "maxIdleMinutes": 15 }'
```

| You send | The realm |
|---|---|
| `If-Match: "<rev>"` that matches | Applies the write |
| `If-Match: "<rev>"` that doesn't match | Answers `412`: read the object again and retry |
| `If-Match: *` | Applies the write if the object exists, whatever its revision |
| No `If-Match` | Applies it, unless the type requires a revision: then `428` |
| `If-None-Match: *` on a `PUT` | Creates the object only if it doesn't exist yet, and answers `412` if it does |

Only the header counts: a `rev` in the body is not a precondition. The Secrets Store has its own check-and-set,
`options.cas`, described in [Check-and-set](../../secrets-store/secrets/check-and-set/).

### Lists replace, maps merge

A `PATCH` with a JSON object is a merge (RFC 7396): the fields you send change, and the rest keep their values.
Inside it, a list and a map behave differently.

<Aside type="caution" title="A list you send replaces the whole list">
  Send every value you want to keep. To add one redirect URI to a client, read its `redirectUris`, add yours, and
  send the whole list back. A list sent with one value leaves one value. The same goes for scopes, origins, grant
  types and every other list, and for every field of a `PUT`, which replaces the whole object.
</Aside>

- **A map is merged key by key** into the stored one, such as a realm's `scopeClaims`. A key sent as `null` is
  removed, and goes back to its default if it has one.
- **A `PATCH` whose body is a JSON array** is a list of RFC 6902 operations (`add`, `remove`, `replace`, …), for a
  change to one item of a list without sending the rest.
- **Every write's body is JSON,** sent as `Content-Type: application/json`. Anything else answers `415`.

### Secrets Store answers

The Secrets Store answers its content under `data`, and a change with nothing to report answers `204`. It answers
`409` (`DISABLED`) until a realm administrator turns it on. The ways to name each owner's vault are in
[Vaults](../../secrets-store/vaults/).

### Field names

Field names are camelCase (`redirectUris`, `maxIdleMinutes`, `validTo`) on every administration API, with two
exceptions:

- **The OAuth 2.0 and OpenID Connect endpoints** under `https://foobar.cvyuh.com/oauth2/` use the standards'
  snake_case names (`grant_type`, `client_id`, `expires_in`).
- **A managed vault's secrets and their metadata** use snake_case: `max_versions`, `cas_required`,
  `delete_version_after`, `custom_metadata`, `created_time`. The rest of the Secrets Store, such as grants and
  emergency access, is camelCase.

## Rate limits

The admin APIs apply no rate limit today: no call is refused for coming too often. That isn't a promise of unlimited
throughput, and a rate limit is planned. Write scripts so they won't break when it arrives:

- **Back off on `429` and `503`.** Wait the number of seconds in `Retry-After` when the answer carries one, and
  otherwise wait a second, then two, then four, before trying again.
- **Keep to a few calls at once.** Page through a large list one page at a time rather than all pages in parallel.
- **Reuse one session.** Signing in again doesn't help; see [Sessions in scripts](#sessions-in-scripts).

The OAuth 2.0 endpoints answer `503` with `temporarily_unavailable` when they can't take a request; retry it later.

## Limits and defaults

| What | Default | Range or cap |
|---|---|---|
| Rate limit on the admin APIs | None | Planned |
| A list's page size | 20 | 1 to 100 |
| A request body | | 10 MiB |
| Sessions per user (`sessionQuota`) | 10 | 1 to 20 |
| A session's lifetime (`maxSessionMinutes`) | 120 minutes | 1 to 43,200 |
| A session's idle window (`maxIdleMinutes`) | 30 minutes | 1 to 1,440 |

Every limit a realm has is in [Limits](/reference/limits/).

## Troubleshooting

- **A script's calls start answering `401` partway through a run.** Its session ended: it reached
  `maxSessionMinutes`, sat idle past `maxIdleMinutes`, or a later sign-in by the same account pushed it past
  `sessionQuota`. Sign in once per run, and sign in again on `401`.
- **The dashboard signs you out while a script runs.** The script signs in as you, and each sign-in past your quota
  ends your oldest session. Give the script its own account.
- **Every write answers `415`.** The body isn't sent as JSON: add `-H "Content-Type: application/json"`.
- **Writes answer `403` from a browser page and work from `curl`.** The page's origin isn't allowed to write with the
  session cookie: see [Allowed origins](/platform/cross-origin/allowed-origins/).

## Errors

An error answers with the status that fits and a body of `code`, `message` and `detail`:

```json
{ "code": "REVISION_CONFLICT", "message": "<what went wrong>", "detail": "<more, when there is more>" }
```

`code` is stable and is what a script should test; `message` is for a person and may change. Two kinds of answer
don't use this shape:

- **A precondition the realm can't apply** (an `If-Match` that doesn't read, a weak tag, `If-Match: *` on a missing
  object, `If-None-Match: *` on one that exists) answers `400` or `412` as an RFC 9457 problem:
  `application/problem+json`, with `type`, `title`, `status` and `detail`.
- **A refusal at the door** (a write whose body isn't JSON, or a write carrying the session cookie from a web origin
  that isn't allowed) answers in plain text.

| Status | Codes | What it means |
|---|---|---|
| `400` | `INVALID_REQUEST`, `MISSING_FIELD`, `SCHEMA_VALIDATION_FAILED`, `POLICY_VIOLATION` | The request doesn't read, or the object doesn't fit its type's schema or rules. `detail` names the field |
| `401` | `UNAUTHORIZED` | No session, or one that has ended. Sign in again |
| `401` | `INVALID_CREDENTIALS` | A sign-in step was answered wrongly |
| `403` | `FORBIDDEN` | Your session is valid, and your rights don't cover this object; or the product isn't turned on for the realm |
| `404` | `NOT_FOUND` | No such object, type or realm, or not one your session can see |
| `405` | `METHOD_NOT_ALLOWED` | The address exists and doesn't take this method |
| `408` | `LOGIN_TIMEOUT` | A sign-in was left too long between steps. Start again |
| `409` | `ALREADY_EXISTS`, `SINGLETON_EXISTS` | An object with that id already exists, or a setting already has its one object |
| `409` | `DISABLED` | The feature is off for the realm until a realm administrator turns it on, such as the Secrets Store |
| `412` | `REVISION_CONFLICT` | The object changed since you read it. Read it again and retry |
| `413` | `PAYLOAD_TOO_LARGE` | The request body is over 10 MiB |
| `415` | | A write whose body isn't JSON |
| `421` | `MISDIRECTED_REQUEST` | The request reached a host other than the one its connection was opened to. Open a connection to that host |
| `428` | `PRECONDITION_REQUIRED` | This type needs `If-Match` on every write |
| `429` | | Not sent today. Once rate limits arrive: too many requests; wait `Retry-After` seconds and retry |
| `502`, `503`, `504` | `UPSTREAM_FAILED`, `UNAVAILABLE`, `UPSTREAM_TIMEOUT` | A part of the realm didn't answer in time. The same request may succeed later |
| `500` | `INTERNAL_ERROR` | Ours, not yours |

## Related

<CardGrid>
  <LinkCard title="Apps and agents" description="The OAuth 2.0 and OpenID Connect endpoints apps and agents call, and the documents they discover them from." href="../apps-and-agents/" />
  <LinkCard title="Delegated administration" description="What decides the rights a session carries." href="../../platform/realms/delegated-administration/" />
  <LinkCard title="Sessions" description="How long a session lasts, and how many one user holds." href="../../workforce-identity/authentication/sessions/" />
  <LinkCard title="Allowed origins" description="Call the API from your own web pages." href="/platform/cross-origin/allowed-origins/" />
</CardGrid>
