> ## 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.

# List API Tokens for Data App

> Retrieve a list of all API tokens associated with a specific Data App.

Get a list of all API tokens for a specific Data App. This is useful for managing and auditing API tokens associated with your Data Apps.

<Warning>
  **Authentication Requirement:** This endpoint requires a **service token** (not a data app API key). Service tokens have elevated permissions to manage API tokens across your organization.
</Warning>

## Endpoint Formats

<Tabs>
  <Tab title="New Endpoint (Recommended)">
    ```
    GET https://api.usedatabrain.com/api/v2/data-app/api-tokens?dataAppName={name}
    ```

    **Use this endpoint** for all new integrations. This is the recommended endpoint format.
  </Tab>

  <Tab title="Legacy Endpoint (Deprecated Soon)">
    ```
    GET https://api.usedatabrain.com/api/v2/dataApp/api-tokens?dataAppName={name}
    ```

    This endpoint still works but will be deprecated. Please migrate to the new endpoint format.
  </Tab>
</Tabs>

## Authentication

This endpoint requires a service token in the Authorization header. Service tokens differ from data app API keys and provide organization-level permissions.

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.

Use this token as the Bearer value in your Authorization header.

## Headers

<ParamField header="Authorization" type="string" required>
  Bearer token for API authentication. Use your service token (not data app API key).

  ```
  Authorization: Bearer service_token_xyz...
  ```
</ParamField>

## Query Parameters

<ParamField query="dataAppName" type="string" required>
  The name of the Data App to list API tokens for. This must exactly match an existing Data App name.

  <Expandable title="Finding Data App names">
    * Use the [List Data Apps](/developer-docs/helpers/api-reference/list-data-apps) API to get all Data App names
    * Check your Databrain dashboard for Data App configurations
    * The name is case-sensitive
  </Expandable>
</ParamField>

<ParamField query="isPagination" type="string">
  Whether to paginate results. Pass `"true"` to enable pagination with a limit of 10 per page.

  **Note:** Query parameters are passed as strings. Use `"true"` or `"false"`.
</ParamField>

<ParamField query="pageNumber" type="string">
  Page number to retrieve (1-based). Only used when isPagination is `"true"`. Must be a numeric string (e.g., `"1"`, `"2"`).
</ParamField>

## Response

<ResponseField name="data" type="array">
  Array of API token objects with their metadata.
</ResponseField>

<ResponseField name="data[].key" type="string">
  The API key value (UUID). Use this key for authentication when making API requests.
</ResponseField>

<ResponseField name="data[].name" type="string">
  The descriptive name/label assigned to the API token when it was created.
</ResponseField>

<ResponseField name="data[].description" type="string">
  The description of the API token, typically indicating the Data App it belongs to.
</ResponseField>

<ResponseField name="data[].createdAt" type="string">
  ISO 8601 formatted timestamp indicating when the API token was created.
</ResponseField>

<ResponseField name="error" type="object">
  Error object returned only when the request fails. Not included in successful responses.

  <Expandable title="error properties">
    <ResponseField name="code" type="string">
      Error code identifying the type of error.
    </ResponseField>

    <ResponseField name="message" type="string">
      Human-readable error message describing what went wrong.
    </ResponseField>
  </Expandable>
</ResponseField>

## Examples

<Panel>
  <RequestExample>
    ```bash cURL - Get All Tokens theme={"dark"}
    curl --request GET \
      --url 'https://api.usedatabrain.com/api/v2/data-app/api-tokens?dataAppName=Customer%20Portal%20Analytics' \
      --header 'Authorization: Bearer service_token_xyz...'
    ```

    ```bash cURL - With Pagination theme={"dark"}
    curl --request GET \
      --url 'https://api.usedatabrain.com/api/v2/data-app/api-tokens?dataAppName=Customer%20Portal%20Analytics&isPagination=true&pageNumber=1' \
      --header 'Authorization: Bearer service_token_xyz...'
    ```

    ```javascript Node.js icon="fa-brands fa-node-js" theme={"dark"}
    const dataAppName = 'Customer Portal Analytics';
    const params = new URLSearchParams({
      dataAppName: dataAppName,
      isPagination: 'true',
      pageNumber: '1'
    });

    const response = await fetch(`https://api.usedatabrain.com/api/v2/data-app/api-tokens?${params}`, {
      method: 'GET',
      headers: {
        'Authorization': 'Bearer service_token_xyz...'
      }
    });

    const data = await response.json();
    console.log('Found API Tokens:', data.data.length);

    data.data.forEach(token => {
      console.log(`- ${token.name} (created: ${token.createdAt})`);
    });
    ```

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

    url = "https://api.usedatabrain.com/api/v2/data-app/api-tokens"
    headers = {
        "Authorization": "Bearer service_token_xyz..."
    }
    params = {
        "dataAppName": "Customer Portal Analytics",
        "isPagination": "true",
        "pageNumber": "1"
    }

    response = requests.get(url, headers=headers, params=params)
    data = response.json()

    print(f"Found API Tokens: {len(data['data'])}")
    for token in data['data']:
        print(f"- {token['name']} (created: {token['createdAt']})")
    ```

    ```java Java icon="fa-brands fa-java" theme={"dark"}
    import java.net.http.HttpClient;
    import java.net.http.HttpRequest;
    import java.net.http.HttpResponse;
    import java.net.URI;
    import java.net.URLEncoder;
    import java.nio.charset.StandardCharsets;

    public class ListApiTokens {
        public static void main(String[] args) throws Exception {
            HttpClient client = HttpClient.newHttpClient();
            
            String dataAppName = URLEncoder.encode("Customer Portal Analytics", StandardCharsets.UTF_8);
            String url = String.format(
                "https://api.usedatabrain.com/api/v2/data-app/api-tokens?dataAppName=%s&isPagination=true&pageNumber=1",
                dataAppName
            );
            
            HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .header("Authorization", "Bearer service_token_xyz...")
                .GET()
                .build();
                
            HttpResponse<String> response = client.send(request, 
                HttpResponse.BodyHandlers.ofString());
                
            System.out.println("Response: " + response.body());
        }
    }
    ```

    ```go Go icon="fa-brands fa-golang" theme={"dark"}
    package main

    import (
        "encoding/json"
        "fmt"
        "net/http"
        "net/url"
    )

    type ApiToken struct {
        Id          string `json:"id"`
        Name        string `json:"name"`
        Description string `json:"description"`
        CreatedAt   string `json:"createdAt"`
    }

    type ListApiTokensResponse struct {
        Data  []ApiToken  `json:"data"`
        Error interface{} `json:"error"`
    }

    func main() {
        baseURL := "https://api.usedatabrain.com/api/v2/data-app/api-tokens"
        params := url.Values{}
        params.Add("dataAppName", "Customer Portal Analytics")
        params.Add("isPagination", "true")
        params.Add("pageNumber", "1")
        
        fullURL := fmt.Sprintf("%s?%s", baseURL, params.Encode())
        
        req, _ := http.NewRequest("GET", fullURL, nil)
        req.Header.Set("Authorization", "Bearer service_token_xyz...")
        
        client := &http.Client{}
        resp, err := client.Do(req)
        if err != nil {
            panic(err)
        }
        defer resp.Body.Close()
        
        var result ListApiTokensResponse
        json.NewDecoder(resp.Body).Decode(&result)
        
        fmt.Printf("Found API Tokens: %d\n", len(result.Data))
        for _, token := range result.Data {
            fmt.Printf("- %s (created: %s)\n", token.Name, token.CreatedAt)
        }
    }
    ```

    ```php PHP icon="fa-brands fa-php" theme={"dark"}
    <?php
    $params = http_build_query([
        'dataAppName' => 'Customer Portal Analytics',
        'isPagination' => 'true',
        'pageNumber' => '1'
    ]);

    $url = 'https://api.usedatabrain.com/api/v2/data-app/api-tokens?' . $params;

    $options = [
        'http' => [
            'header' => 'Authorization: Bearer service_token_xyz...',
            'method' => 'GET'
        ]
    ];

    $context = stream_context_create($options);
    $result = file_get_contents($url, false, $context);
    $response = json_decode($result, true);

    echo "Found API Tokens: " . count($response['data']) . "\n";
    foreach ($response['data'] as $token) {
        echo "- " . $token['name'] . " (created: " . $token['createdAt'] . ")\n";
    }
    ?>
    ```

    ```ruby Ruby icon="fa-solid fa-gem" theme={"dark"}
    require 'net/http'
    require 'json'

    uri = URI('https://api.usedatabrain.com/api/v2/data-app/api-tokens')
    params = {
      dataAppName: 'Customer Portal Analytics',
      isPagination: 'true',
      pageNumber: '1'
    }
    uri.query = URI.encode_www_form(params)

    http = Net::HTTP.new(uri.host, uri.port)
    http.use_ssl = true

    request = Net::HTTP::Get.new(uri)
    request['Authorization'] = 'Bearer service_token_xyz...'

    response = http.request(request)
    result = JSON.parse(response.body)

    puts "Found API Tokens: #{result['data'].length}"
    result['data'].each do |token|
      puts "- #{token['name']} (created: #{token['createdAt']})"
    end
    ```
  </RequestExample>

  <ResponseExample>
    ```json 200 - Success theme={"dark"}
    {
      "data": [
        {
          "key": "550e8400-e29b-41d4-a716-446655440000",
          "name": "Production API Key",
          "description": "API key for data app Customer Portal Analytics",
          "createdAt": "2024-01-15T10:30:00Z"
        },
        {
          "key": "7c9e6679-7425-40de-944b-e07fc1f90ae7",
          "name": "Development Token",
          "description": "API key for data app Customer Portal Analytics",
          "createdAt": "2024-01-10T14:15:00Z"
        },
        {
          "key": "9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d",
          "name": "Staging Environment",
          "description": "API key for data app Customer Portal Analytics",
          "createdAt": "2024-01-08T09:00:00Z"
        }
      ]
    }
    ```

    ```json 400 - Invalid Request Body theme={"dark"}
    {
      "error": {
        "code": "INVALID_REQUEST_BODY",
        "message": "\"dataAppName\" is required"
      }
    }
    ```

    ```json 400 - Data App Not Found theme={"dark"}
    {
      "error": {
        "code": "DATA_APP_NOT_FOUND",
        "message": "Data app not found"
      }
    }
    ```

    ```json 400 - Invalid Service Token theme={"dark"}
    {
      "error": {
        "code": "AUTHENTICATION_ERROR",
        "message": "Invalid Service Token"
      }
    }
    ```

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

## HTTP Status Code Summary

| Status Code | Description                                       |
| ----------- | ------------------------------------------------- |
| `200`       | **OK** - API tokens retrieved successfully        |
| `400`       | **Bad Request** - Invalid request parameters      |
| `500`       | **Internal Server Error** - Server error occurred |

## Possible Errors

| Error Code              | HTTP Status | Description                        |
| ----------------------- | ----------- | ---------------------------------- |
| `INVALID_REQUEST_BODY`  | 400         | Missing or invalid dataAppName     |
| `DATA_APP_NOT_FOUND`    | 400         | Data App with given name not found |
| `AUTHENTICATION_ERROR`  | 400         | Invalid or missing service token   |
| `INTERNAL_SERVER_ERROR` | 500         | Server error                       |

## Quick Start Guide

<Steps>
  <Step title="Get your service token">
    In **Settings** page, navigate to the **Service Tokens** section. Click the **"Generate Token"** button to create a new service token if you don't have one already.
  </Step>

  <Step title="Identify the Data App">
    Use the [List Data Apps](/developer-docs/helpers/api-reference/list-data-apps) API to find the Data App name:

    ```bash theme={"dark"}
    curl --request GET \
      --url 'https://api.usedatabrain.com/api/v2/data-app' \
      --header 'Authorization: Bearer service_token_xyz...'
    ```
  </Step>

  <Step title="List API tokens">
    Get all API tokens for the Data App:

    ```bash theme={"dark"}
    curl --request GET \
      --url 'https://api.usedatabrain.com/api/v2/data-app/api-tokens?dataAppName=My%20Data%20App' \
      --header 'Authorization: Bearer service_token_xyz...'
    ```
  </Step>

  <Step title="Manage your tokens">
    Use the token information to manage your API keys:

    ```javascript theme={"dark"}
    const tokens = await listApiTokens({ dataAppName: 'My Data App' });

    tokens.data.forEach(token => {
      console.log(`Token: ${token.name}`);
      console.log(`  Key: ${token.key}`);
      console.log(`  Created: ${token.createdAt}`);
      
      // Check if token is old and might need rotation
      const createdDate = new Date(token.createdAt);
      const daysSinceCreation = (Date.now() - createdDate) / (1000 * 60 * 60 * 24);
      
      if (daysSinceCreation > 90) {
        console.log(`  ⚠️ Consider rotating this token (${Math.floor(daysSinceCreation)} days old)`);
      }
    });
    ```
  </Step>
</Steps>

## Next Steps

<CardGroup cols={2}>
  <Card title="Create API Token" icon="plus" href="/developer-docs/helpers/api-reference/create-api-token">
    Generate new API tokens for your Data Apps
  </Card>

  <Card title="Rotate API Key" icon="rotate" href="/developer-docs/helpers/api-reference/rotate-api-key">
    Rotate API keys for enhanced security
  </Card>

  <Card title="List Data Apps" icon="list" href="/developer-docs/helpers/api-reference/list-data-apps">
    View all Data Apps in your organization
  </Card>

  <Card title="Create Embed" icon="code" href="/developer-docs/helpers/api-reference/create-embed">
    Use your API tokens to create embed configurations
  </Card>
</CardGroup>
