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

# Create API Token for Data App

> Generate a new API token for a specific Data App to enable embed operations.

Create a new API token for a Data App. API tokens are used to authenticate requests for embed operations such as creating embeds, generating guest tokens, and querying metrics.

<Note>
  Each Data App can have multiple API tokens. This is useful for:

  * Separating tokens by environment (development, staging, production)
  * Rotating tokens without service interruption
  * Tracking API usage by token
</Note>

<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)">
    ```
    POST https://api.usedatabrain.com/api/v2/data-app/api-tokens
    ```

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

  <Tab title="Legacy Endpoint (Deprecated Soon)">
    ```
    POST https://api.usedatabrain.com/api/v2/dataApp/api-tokens
    ```

    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>

<ParamField header="Content-Type" type="string" required>
  Must be set to `application/json` for all requests.

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

## Request Body

<ParamField body="dataAppName" type="string" required>
  The name of the Data App to create the API token 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 body="name" type="string" required>
  A descriptive name/label for the API token. This helps identify the token's purpose.

  <Expandable title="Naming recommendations">
    * Use descriptive names like "Production Token", "Development Token", "Partner API Key"
    * Include environment or purpose information
    * Keep names unique within each Data App for easy identification
  </Expandable>
</ParamField>

## Response

<ResponseField name="key" type="string">
  The newly generated API token (UUID format). Store this securely as it will be used for all embed operations.

  <Warning>
    **Important:** The API key is only shown once. Store it securely immediately after creation.
  </Warning>
</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 theme={"dark"}
    curl --request POST \
      --url https://api.usedatabrain.com/api/v2/data-app/api-tokens \
      --header 'Authorization: Bearer service_token_xyz...' \
      --header 'Content-Type: application/json' \
      --data '{
        "dataAppName": "Customer Portal Analytics",
        "name": "Production API Key"
      }'
    ```

    ```javascript Node.js icon="fa-brands fa-node-js" theme={"dark"}
    const response = await fetch('https://api.usedatabrain.com/api/v2/data-app/api-tokens', {
      method: 'POST',
      headers: {
        'Authorization': 'Bearer service_token_xyz...',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        dataAppName: 'Customer Portal Analytics',
        name: 'Production API Key'
      })
    });

    const data = await response.json();
    console.log('New API Key:', data.key);
    // Store this key securely!
    ```

    ```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...",
        "Content-Type": "application/json"
    }
    payload = {
        "dataAppName": "Customer Portal Analytics",
        "name": "Production API Key"
    }

    response = requests.post(url, headers=headers, json=payload)
    data = response.json()
    print(f"New API Key: {data['key']}")
    # Store this key securely!
    ```

    ```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;

    public class CreateApiToken {
        public static void main(String[] args) throws Exception {
            HttpClient client = HttpClient.newHttpClient();
            
            String requestBody = """
                {
                    "dataAppName": "Customer Portal Analytics",
                    "name": "Production API Key"
                }""";
            
            HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://api.usedatabrain.com/api/v2/data-app/api-tokens"))
                .header("Authorization", "Bearer service_token_xyz...")
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(requestBody))
                .build();
                
            HttpResponse<String> response = client.send(request, 
                HttpResponse.BodyHandlers.ofString());
                
            System.out.println("Response: " + response.body());
            // Store the key securely!
        }
    }
    ```

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

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

    type CreateApiTokenRequest struct {
        DataAppName string `json:"dataAppName"`
        Name        string `json:"name"`
    }

    type CreateApiTokenResponse struct {
        Key   string      `json:"key"`
        Error interface{} `json:"error"`
    }

    func main() {
        requestBody := CreateApiTokenRequest{
            DataAppName: "Customer Portal Analytics",
            Name:        "Production API Key",
        }

        jsonData, _ := json.Marshal(requestBody)
        
        req, _ := http.NewRequest("POST", "https://api.usedatabrain.com/api/v2/data-app/api-tokens", bytes.NewBuffer(jsonData))
        req.Header.Set("Authorization", "Bearer service_token_xyz...")
        req.Header.Set("Content-Type", "application/json")

        client := &http.Client{}
        resp, _ := client.Do(req)
        defer resp.Body.Close()

        var result CreateApiTokenResponse
        json.NewDecoder(resp.Body).Decode(&result)
        fmt.Printf("New API Key: %s\n", result.Key)
        // Store this key securely!
    }
    ```

    ```php PHP icon="fa-brands fa-php" theme={"dark"}
    <?php
    $curl = curl_init();

    $data = [
        'dataAppName' => 'Customer Portal Analytics',
        'name' => 'Production API Key'
    ];

    curl_setopt_array($curl, [
        CURLOPT_URL => 'https://api.usedatabrain.com/api/v2/data-app/api-tokens',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_POSTFIELDS => json_encode($data),
        CURLOPT_HTTPHEADER => [
            'Authorization: Bearer service_token_xyz...',
            'Content-Type: application/json'
        ],
    ]);

    $response = curl_exec($curl);
    curl_close($curl);

    $result = json_decode($response, true);
    echo 'New API Key: ' . $result['key'];
    // Store this key securely!
    ?>
    ```

    ```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')
    http = Net::HTTP.new(uri.host, uri.port)
    http.use_ssl = true

    request = Net::HTTP::Post.new(uri)
    request['Authorization'] = 'Bearer service_token_xyz...'
    request['Content-Type'] = 'application/json'

    request.body = {
      dataAppName: 'Customer Portal Analytics',
      name: 'Production API Key'
    }.to_json

    response = http.request(request)
    result = JSON.parse(response.body)
    puts "New API Key: #{result['key']}"
    # Store this key securely!
    ```
  </RequestExample>

  <ResponseExample>
    ```json 200 - Success theme={"dark"}
    {
      "key": "550e8400-e29b-41d4-a716-446655440000"
    }
    ```

    ```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 token created 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 or name |
| `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                           |

## API Token Scope

When an API token is created, it is automatically assigned the following scope:

* **Access Metrics** - Query and retrieve metric data
* **Access Dashboards** - Access and embed dashboards

## 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="Verify the Data App exists">
    Use the [List Data Apps](/developer-docs/helpers/api-reference/list-data-apps) API to confirm the Data App exists:

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

  <Step title="Create the API token">
    Create a new API token for your Data App:

    ```bash theme={"dark"}
    curl --request POST \
      --url https://api.usedatabrain.com/api/v2/data-app/api-tokens \
      --header 'Authorization: Bearer service_token_xyz...' \
      --header 'Content-Type: application/json' \
      --data '{"dataAppName": "My Data App", "name": "Production Token"}'
    ```
  </Step>

  <Step title="Store the API key securely">
    The response contains the API key. Store it securely as it won't be shown again:

    ```javascript theme={"dark"}
    // Store in environment variables
    process.env.DATABRAIN_API_KEY = response.key;

    // Or in a secrets manager
    await secretsManager.setSecret('databrain-api-key', response.key);
    ```
  </Step>

  <Step title="Use the API key for embed operations">
    Use the new API key to create embeds and generate guest tokens:

    ```bash theme={"dark"}
    curl --request POST \
      --url 'https://api.usedatabrain.com/api/v2/data-app/embeds' \
      --header 'Authorization: Bearer 550e8400-e29b-41d4-a716-446655440000' \
      --header 'Content-Type: application/json' \
      --data '{...}'
    ```
  </Step>
</Steps>

## Best Practices

<CardGroup cols={2}>
  <Card title="Store Keys Securely" icon="lock">
    Never commit API keys to version control. Use environment variables or secrets managers.
  </Card>

  <Card title="Use Descriptive Names" icon="tag">
    Name tokens clearly (e.g., "Production API Key", "Dev Environment Token")
  </Card>

  <Card title="Rotate Regularly" icon="rotate">
    Rotate API keys periodically for enhanced security using the [Rotate API Key](/developer-docs/helpers/api-reference/rotate-api-key) endpoint.
  </Card>

  <Card title="Separate by Environment" icon="layer-group">
    Create separate tokens for development, staging, and production environments.
  </Card>
</CardGroup>

## Next Steps

<CardGroup cols={2}>
  <Card title="List API Tokens" icon="list" href="/developer-docs/helpers/api-reference/list-api-tokens">
    View all API tokens for a Data App
  </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="Create Embed" icon="code" href="/developer-docs/helpers/api-reference/create-embed">
    Use your API token to create embed configurations
  </Card>

  <Card title="Generate Guest Token" icon="ticket" href="/developer-docs/helpers/api-reference/token">
    Generate guest tokens for your end users
  </Card>
</CardGroup>
