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

# 2. Managing and deleting API tokens

> [!WARNING]
>
> You are viewing the documentation of release 26.1, which is no longer the current one. [Go to the documentation of the current release 26.2](https://developers.circularo.com/).

## API Token Management Overview

API tokens provide long-lived authentication for integrations, but proper management is essential for security. This scenario demonstrates how to list all your active API tokens and delete those that are no longer needed.

**Key benefits of token management:**

* Regular auditing of active tokens helps maintain security
* Removing unused tokens reduces potential attack surface
* Token management is a critical part of security best practices
* Each user can have multiple API tokens active simultaneously

> [!WARNING]
>
> Deleting an API token immediately invalidates it and any integrations using that token will stop working. Make sure you're deleting the correct token.

## Step 1 - Authenticate user to access token management *(Optional)*

Before managing your API tokens, you need to authenticate with your username and password to obtain a session token.

> [!NOTE]
>
> If you already have a valid API token, you can use that instead of logging in with username and password.

**Endpoint**

```http theme={null}
POST /login
```

**Request**

```http theme={null}
POST /login

Content-Type: application/json

{
  "name": "mary.griffin@circularo.com",
  "password": "#32Password1!",
  "returnToken": true
}
```

**Response**

```json theme={null}
{
  "logged": true,
  "isUnlocked": true,
  "token": "9rg0M3I4B64yajvt2jfiBqF6hKJY3u5MugcFkpjyGOT4rIrJKnN1fvayPNi6EN88",
  "tenant": "default",
  "user": {
    ...
  },
  "settings": {
    ...
  },
  "rights": [
    ...
  ],
  ...
}
```

The response contains the following important properties:

* **token** - Located at `token` in the response.
  * The authentication token that should be included in subsequent API requests. This token identifies your session and provides access to authorized resources.
  * Example value: `9rg0M3I4B64yajvt2jfiBqF6hKJY3u5MugcFkpjyGOT4rIrJKnN1fvayPNi6EN88`

Authentication successful. The response includes a session token that will be used to list and manage your API tokens.

## Step 2 - List all active API tokens

Retrieves a list of all active API tokens for your account. This is an important first step in token management and security auditing.

* Regular auditing of your active tokens is a security best practice
* Each token shows when it was created and last used
* Identify tokens that may no longer be needed or could be compromised
* Use this information to decide which tokens to revoke

> [!NOTE]
>
> Consider implementing a regular schedule for reviewing your active API tokens as part of your security practices.

**Endpoint**

```http theme={null}
GET /api/key
```

**Request**

```http theme={null}
GET /api/key?token=9rg0M3I4B64yajvt2jfiBqF6hKJY3u5MugcFkpjyGOT4rIrJKnN1fvayPNi6EN88
```

**Response**

```json theme={null}
{
  "results": [
    {
      "id": "VlzlS633OQD2PC290D2a1xjlAGFrE28e95Ob7nhPaAWhOxYdx25QzBFPJjisrNB7",
      "description": "API token for server-to-server authentication",
      "created": "2023-01-15T10:30:45Z",
      "lastUsed": "2023-06-20T14:22:10Z",
      "apiKeyType": "generic"
    },
    {
      "id": "p62g0MLNKUBIB7AaHkpFmsJsrKpJxabVmLDoY4nCelD6AK7SWiMXkVzsGNRfedrZ",
      "description": "Token for CI/CD pipeline",
      "created": "2023-03-10T08:15:30Z",
      "lastUsed": "2023-06-21T09:45:22Z",
      "apiKeyType": "generic"
    }
  ]
}
```

The response contains the following important properties:

* **apiToken** - Located at `results[0].id` in the response.
  * The unique identifier of an API token.
  * Example value: `VlzlS633OQD2PC290D2a1xjlAGFrE28e95Ob7nhPaAWhOxYdx25QzBFPJjisrNB7`

The response contains an array of all active API tokens for your account. Each token includes:

* A unique identifier that can be used to revoke the token
* Creation timestamp showing when the token was generated
* Last usage information to identify potentially unused tokens
* Human readable description of the token, provided during the token creation

> [!NOTE]
>
> Tokens that haven't been used recently or were created for temporary purposes are good candidates for deletion.

## Step 3 - Revoke an API token

Permanently invalidates an API token that is no longer needed. Once revoked, the token cannot be used for authentication and any systems using it will lose access.

* Revoking unused tokens is a security best practice
* Tokens should be revoked when an integration is decommissioned
* Consider revoking and replacing tokens periodically as part of security rotation
* There is no way to reactivate a token once it's been revoked - you'll need to create a new one

> [!WARNING]
>
> This action cannot be undone. Any systems using this token will immediately lose access to your account.

**Endpoint**

```http theme={null}
DELETE /api/key/:token
```

**Request**

```http theme={null}
DELETE /api/key/VlzlS633OQD2PC290D2a1xjlAGFrE28e95Ob7nhPaAWhOxYdx25QzBFPJjisrNB7
```

The API token has been successfully revoked and can no longer be used for authentication.

> [!NOTE]
>
> If you accidentally revoke the wrong token, you'll need to create a new one and update any affected integrations.

## Step 4 - End the management session *(Optional)*

Terminates your current session after completing the token management tasks.

**Endpoint**

```http theme={null}
GET /logout
```

**Request**

```http theme={null}
GET /logout?token=9rg0M3I4B64yajvt2jfiBqF6hKJY3u5MugcFkpjyGOT4rIrJKnN1fvayPNi6EN88
```

The session has been successfully terminated. Your account security is maintained by not leaving active sessions.

***

## API Token Management Best Practices

Regular auditing and management of your API tokens is an essential security practice:

* List and review your active tokens on a regular schedule
* Revoke any tokens that are no longer being used
* Replace long-lived tokens periodically, especially for critical systems

### Example Token Management Code

> [!NOTE]
>
> See our OpenAPI documentation to learn about the full set of API endpoints and parameters.

> [!NOTE]
>
> Please use proper exception handling and function decomposition in your own code. The code is provided for illustrative purposes only and is not intended for production use.

```javascript theme={null}
// List API tokens and delete the unused ones
const URL = "https://sandbox.circularo.com";
const API_PATH = "/api/v1";

const name = "YOUR_NAME/EMAIL";
const password = "YOUR_PASSWORD";

try {
    // Step 1: Login to get session token
    const loginResponse = await fetch(`${URL}${API_PATH}/login`, {
        method: 'POST',
        body: JSON.stringify({ name, password, returnToken: true }),
        headers: { 'Content-Type': 'application/json' }
    });
    if (!loginResponse.ok) {
        throw new Error(`Login failed: ${loginResponse.status} ${loginResponse.statusText}`);
    }
    const { token } = await loginResponse.json();

    // Step 2: List all active API tokens
    const listTokensResponse = await fetch(`${URL}${API_PATH}/api/key?token=${token}`);
    if (!listTokensResponse.ok) {
        throw new Error(`Token fetch failed: ${listTokensResponse.status} ${listTokensResponse.statusText}`);
    }
    const { results: apiTokens } = await listTokensResponse.json();

    // Step 3: Find unused tokens (example logic - customize as needed)
    // tokens not used in the last 90 days
    const ninetyDaysAgo = new Date();
    ninetyDaysAgo.setDate(ninetyDaysAgo.getDate() - 90);
    const unusedTokens = apiTokens.filter((token) => {
        const lastUsed = new Date(token.lastUsed);
        return (lastUsed < ninetyDaysAgo);
    });

    // Step 4: Revoke unused tokens
    for (const tokenToDelete of unusedTokens) {
        const deleteResponse = await fetch(`${URL}${API_PATH}/api/key/${tokenToDelete.id}`, {
            method: 'DELETE'
        });

        if (!deleteResponse.ok) {
            console.error(`Failed to revoke API token: ${tokenToDelete.id}`);
        } else {
            console.log(`Revoked unused API token: ${tokenToDelete.id}`);
        }
    }

    // Step 5: Logout the session
    await fetch(`${URL}${API_PATH}/logout?token=${token}`);

} catch (error) {
    console.error('Error in API Token revocation flow:', error.message);
}
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.