> For the complete documentation index, see [llms.txt](https://docs.silkline.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.silkline.ai/administration-tools/api.md).

# API

Learn how to authenticate and access the Silkline GraphQL API. This guide covers creating API keys, exchanging them for JWT tokens, and making authenticated requests.

## Silkline API Documentation

{% hint style="warning" %}
**Limited Beta Access**\
Silkline API is currently in limited beta for select customers. Please discuss your use case with us to ensure success for both parties. Each API key is rate limited; see [Rate limits](#rate-limits).
{% endhint %}

### Getting Started

API access is granted through **API keys**. Each key is a `clientId` and `clientSecret` pair that your integration exchanges for a short-lived access token.

1. Ask Silkline to enable API keys for your organization. Once enabled, **Organization Settings → API keys** appears in your settings menu.
2. A user with the **Create API Key** permission (held by the Admin role by default) creates a key on that page and gives it a name.
3. Copy the `clientId` and `clientSecret` shown at creation. The secret is displayed once and cannot be retrieved later; if it is lost, create a new key and delete the old one.

See [API Keys](https://docs.silkline.ai/profile-and-settings/organization-settings/api-keys.md) for the full guide to creating and deleting keys.

### Authentication

#### Step 1: Exchange Credentials for JWT Token

Use your credentials to obtain a JWT token from the token endpoint:

**Production:**

```bash
curl -X POST https://app.silkline.ai/api/oauth/token \
  -H "Content-Type: application/json" \
  -d '{
    "client_id": "<clientId>",
    "client_secret": "<clientSecret>",
    "grant_type": "client_credentials"
  }'
```

**Development:**

```bash
curl -X POST https://dev-app-gov.silkline.ai/api/oauth/token \
  -H "Content-Type: application/json" \
  -d '{
    "client_id": "<clientId>",
    "client_secret": "<clientSecret>",
    "grant_type": "client_credentials"
  }'
```

The endpoint also accepts a form-encoded body (`application/x-www-form-urlencoded`) and HTTP Basic authentication, where the client ID and secret are sent in the `Authorization` header instead of the body:

```bash
curl -X POST https://app.silkline.ai/api/oauth/token \
  -u "<clientId>:<clientSecret>" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=client_credentials"
```

**Response:**

```json
{
  "access_token": "eyJ0eXAiOiJKV1...",
  "token_type": "Bearer",
  "expires_in": 86400
}
```

**Important Notes:**

* No `audience` parameter is required
* Tokens are valid for 24 hours. As much as possible, please reuse the same token for multiple requests rather than generating a new token for each API call
* Your token is scoped to your organization with the same permissions as an admin user
* Deleting a key stops it from obtaining new tokens. A token already issued stays valid until it expires

#### Step 2: Access the GraphQL API

Use your token to make GraphQL requests:

```bash
curl -X POST https://app.silkline.ai/api/graphql \
  -H "Authorization: Bearer <access_token>" \
  -H "Content-Type: application/json" \
  -d '{
    "query": "{ Order { id } }"
  }'
```

Replace `<access_token>` with the token received in Step 1.

{% hint style="info" %}
**Note:** While mutations are available, we strongly encourage limiting your usage to queries only
{% endhint %}

### Rate limits

Each API key can make up to **3,000 requests per minute**, counted over a rolling one-minute window. The limit applies to the key alone: other keys and users in your organization are unaffected.

A request over the limit returns HTTP `200` with a GraphQL error whose `extensions.code` is `rate-limit-exceeded`:

```json
{
  "errors": [
    {
      "message": "rate limit of 3000 exceeded",
      "extensions": { "path": "$", "code": "rate-limit-exceeded" }
    }
  ]
}
```

When you receive this error, wait and retry with exponential backoff. Spread bulk syncs over time rather than sending them in a single burst.

### Query limits

Each request made with an API key must stay within these limits:

| Limit                                                                            | Maximum    | Error code             |
| -------------------------------------------------------------------------------- | ---------- | ---------------------- |
| Depth: nested fields that select other fields, counting the top-level field as 1 | 8          | `depth-limit-exceeded` |
| Nodes: fields in the query that select other fields                              | 150        | `node-limit-exceeded`  |
| Operations in one batched request                                                | 10         | `batch-limit-exceeded` |
| Execution time                                                                   | 30 seconds | `time-limit-exceeded`  |

Fields that return a plain value, such as `id` or `name`, don't count toward depth or nodes. A request over a limit returns a GraphQL error with the code above. A query over the depth or node limit is rejected before it runs. Split it into smaller queries, or paginate with `limit` and `offset`.

### Example: export your security settings

This query returns your organization's security-relevant settings, its administrators, its API keys, its published Public Files, and its custom file storage. Compare the result with the secure defaults in the [Secure Configuration Guide](https://github.com/Silkline/client-app/tree/development/docs/configuration/secure-configuration-guide.md#secure-defaults), and keep the JSON response as a record of each review. A `defaultRoleId` of `null` means new members get the Viewer role.

```graphql
query SecuritySettings {
  OrganizationSetting {
    defaultRoleId
    sendOnBehalf
    apiKeysEnabled: features(path: "$.isApiKeysEnabled.enabled")
    domains
  }
  OrganizationUserToRole(where: { Role: { name: { _eq: "Admin" } } }) {
    OrganizationUser {
      userName
      isArchived
      User {
        email
      }
    }
  }
  OrganizationApiKey {
    name
    createdAt
    lastTokenIssuedAt
  }
  OrganizationHostedFile(where: { isPublished: { _eq: true } }) {
    label
    slug
  }
  OrganizationFileStorageConfig {
    bucketName
    region
  }
}
```

### Example: compare your settings with the secure defaults

The secure defaults are published as JSON at `https://app.silkline.ai/.well-known/fedramp/secure-configuration-guide`. The document includes the query above as `settingsQuery`. Each entry in `defaults` lists `checks`: the response field to read (`apiField`) and how to compare it (`comparison`). Entries without checks need a manual review.

This script runs the query and prints each check as `true` (matches the default), `false` (differs), or `manual`. It stops with an error if the query fails, for example when the access token has expired:

```bash
curl -s https://app.silkline.ai/.well-known/fedramp/secure-configuration-guide \
  > defaults.json

jq '{query: .settingsQuery}' defaults.json |
  curl -s -X POST https://app.silkline.ai/api/graphql \
    -H "Authorization: Bearer <access_token>" \
    -H "Content-Type: application/json" \
    -d @- > settings.json

jq -r --slurpfile settings settings.json '
  def at($path):
    reduce ($path | split(".")[]) as $key (.;
      (if type == "array" then .[0] else . end) | .[$key]);
  $settings[0] as $response
  | if ($response.errors // []) != []
      or ($response.data.OrganizationSetting | length) != 1
    then error("Settings query failed: \($response.errors // "no settings")")
    else . end
  | .defaults[] | .setting as $setting
  | if .checks == [] then "\($setting)\t-\tmanual"
    else .checks[] | . as $check
      | ($response.data | at($check.apiField)) as $value
      | if $check.comparison == "equals" then $value == $check.expected
        elif $check.comparison == "isNull" then $value == null
        elif $check.comparison == "empty" then $value == []
        elif $check.comparison == "notTrue" then $value != true
        else "manual" end
      | "\($setting)\t\($check.apiField)\t\(.)"
    end
' defaults.json
```

A `false` result is not always a problem. Record the approved exception, as described in the guide.
