> ## Documentation Index
> Fetch the complete documentation index at: https://docs.usedatabrain.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Rotate Service Token

> Rotate your service token. Expires the current token after an optional grace period and returns a new token.

Rotate your organization service token. The current token is set to expire after a grace period (in seconds), and a new service token is returned. Use this for key rotation and security best practices.

<Note>
  The service token used in the `Authorization` header **is** the token being rotated. You only need to provide `expireAt` in the request body — no `token` field required.
</Note>

## Authentication

Use your current **service token** in the `Authorization` header. The token provided here is the one that will be expired and replaced.

To access your service token:

1. In **Settings** page, navigate to the **Service Tokens** section.
2. Click the **"Generate Token"** button to create a new service token if you don't have one already.

## Headers

<ParamField header="Authorization" type="string" required>
  Bearer token for API authentication. Use the **service token** you want to rotate.

  ```
  Authorization: Bearer 550e8400-e29b-41d4-a716-446655440000
  ```
</ParamField>

<ParamField header="Content-Type" type="string" required>
  Must be `application/json` when sending a JSON body.

  ```
  Content-Type: application/json
  ```
</ParamField>

## Request Body

<ParamField body="expireAt" type="number | string" required>
  Duration in **seconds** until the current token expires. The old token remains valid until this many seconds from the request, then it is invalidated. Accepts a number or a numeric string. Use `0` to expire immediately. Common values: `0` (immediate), `3600` (1 hour), `86400` (24 hours).
</ParamField>

## Response

On success, the API returns **200** with a JSON object:

<ResponseField name="key" type="string">
  The new service token (UUID). Use this for all future service-level API calls. Store it securely; the previous token will expire per `expireAt`.
</ResponseField>

On error, the API returns a JSON object with `error.code` and `error.message` and an appropriate HTTP status (400, 401, or 500).

## Examples

<Panel>
  <RequestExample>
    ```bash cURL theme={"dark"}
    curl --request POST \
      --url https://api.usedatabrain.com/api/v2/service-token/rotate \
      --header 'Authorization: Bearer 550e8400-e29b-41d4-a716-446655440000' \
      --header 'Content-Type: application/json' \
      --data '{"expireAt":3600}'
    ```

    ```javascript Node.js icon="fa-brands fa-node-js" theme={"dark"}
    const response = await fetch('https://api.usedatabrain.com/api/v2/service-token/rotate', {
      method: 'POST',
      headers: {
        'Authorization': 'Bearer 550e8400-e29b-41d4-a716-446655440000',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        expireAt: 3600
      })
    });
    const data = await response.json();
    if (data.error) throw new Error(data.error.message);
    console.log('New service token:', data.key);
    ```

    ```python Python icon="fa-brands fa-python" theme={"dark"}
    import requests

    url = "https://api.usedatabrain.com/api/v2/service-token/rotate"
    headers = {
        "Authorization": "Bearer 550e8400-e29b-41d4-a716-446655440000",
        "Content-Type": "application/json"
    }
    payload = {
        "expireAt": 3600
    }

    response = requests.post(url, headers=headers, json=payload)
    data = response.json()
    if data.get("error"):
        raise Exception(data["error"].get("message", "Request failed"))
    print("New service token:", data["key"])
    ```
  </RequestExample>

  <ResponseExample>
    ```json Success (200) theme={"dark"}
    {
      "key": "7c9e6679-7425-40de-944b-e07fc1f90ae7"
    }
    ```

    ```json Error (400) - Invalid request body theme={"dark"}
    {
      "error": {
        "code": "INVALID_REQUEST_BODY",
        "message": "\"expireAt\" is required"
      }
    }
    ```

    ```json Error (400) - Invalid API key format theme={"dark"}
    {
      "error": {
        "code": "AUTHENTICATION_ERROR",
        "message": "API Key is not provided or Invalid!"
      }
    }
    ```

    ```json Error (401) - API key not found or expired theme={"dark"}
    {
      "error": {
        "code": "AUTHENTICATION_ERROR",
        "message": "API Key is invalid or expired!"
      }
    }
    ```

    ```json Error (400) - Not a service token theme={"dark"}
    {
      "error": {
        "code": "AUTHENTICATION_ERROR",
        "message": "Invalid Service Token"
      }
    }
    ```

    ```json Error (400) - Token already expired theme={"dark"}
    {
      "error": {
        "code": "EXPIRED_SERVICE_TOKEN",
        "message": "Service token is already expired"
      }
    }
    ```

    ```json Error (500) theme={"dark"}
    {
      "error": {
        "code": "INTERNAL_SERVER_ERROR",
        "message": "Internal server error"
      }
    }
    ```
  </ResponseExample>
</Panel>

## HTTP Status Code Summary

| Status Code | Description                                                                                             |
| ----------- | ------------------------------------------------------------------------------------------------------- |
| `200`       | **OK** – New service token returned in `key`                                                            |
| `400`       | **Bad Request** – Missing parameters, invalid key format, not a service token, or token already expired |
| `401`       | **Unauthorized** – Service token not found in DB or already expired                                     |
| `500`       | **Internal Server Error** – Server error                                                                |

## Possible Errors

| Code                    | Message                                                                                                                                                                                                                            | HTTP Status |
| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- |
| `INVALID_REQUEST_BODY`  | Joi validation message (e.g. `"expireAt" is required`)                                                                                                                                                                             | 400         |
| `AUTHENTICATION_ERROR`  | `"API Key is not provided or Invalid!"` – missing/invalid UUID format (400); `"API Key is invalid or expired!"` – not found or expired in DB (401); `"Invalid Service Token"` – token is a data app key, not a service token (400) | 400 / 401   |
| `EXPIRED_SERVICE_TOKEN` | Service token is already expired                                                                                                                                                                                                   | 400         |
| `INVALID_SERVICE_TOKEN` | Invalid service token                                                                                                                                                                                                              | 400         |
| `INTERNAL_SERVER_ERROR` | Internal server error or GraphQL error message                                                                                                                                                                                     | 500         |

## Related

* [Create Service Token](/developer-docs/helpers/api-reference/create-service-token) – Create or save a service token
* [Rotate API Key](/developer-docs/helpers/api-reference/rotate-api-key) – Rotate a data app API key
* [Create Admin JWT](/developer-docs/helpers/api-reference/create-admin-jwt) – Get admin access token
