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

# API credentials

> Learn how to access SQL and REST API credentials for connecting BI tools, applications, and SQL clients to your cubes

**Focus:** Understand how to access and use API credentials to connect BI tools, custom applications, and SQL clients to your Metrics Store cubes.

API credentials provide secure access to your cubes through SQL and REST APIs. These credentials enable you to connect external tools, applications, and clients to query your cube data programmatically.

## Accessing API credentials

### **Opening credentials drawer**

1. **Click "API Credentials" button** in the Metrics Store header
2. **Credentials drawer opens** showing available APIs
3. **View credentials** for SQL API and REST API

### **Prerequisites**

API credentials are available when:

* ✅ A project is selected
* ✅ A branch is selected
* ✅ Server heartbeat status is **"RUNNING"**
* ✅ Server has been initialized

<Note>
  **Credentials availability**

  If the API Credentials button is disabled or shows no data, ensure the server heartbeat has reached **"RUNNING"** status. Credentials are generated after the server successfully starts.
</Note>

## SQL API credentials

### **Overview**

SQL API provides PostgreSQL-compatible connection for BI tools and SQL clients:

* **PostgreSQL protocol** - Standard SQL interface
* **BI tool integration** - Connect Tableau, Power BI, Looker, etc.
* **SQL client support** - Use with any PostgreSQL-compatible client
* **Direct querying** - Execute SQL queries against your cubes

### **Connection components**

**Connection string**

* Complete PostgreSQL connection URL
* Includes all connection parameters
* Ready to use in connection dialogs

**Individual credentials:**

* **Host** - Server hostname or IP address
* **Port** - Database port number
* **Database** - Database name
* **Username** - Authentication username
* **Password** - Authentication password

### **Using SQL API credentials**

#### **Connect BI tools**

1. **Copy connection string** or individual credentials
2. **Open BI tool connection dialog**
3. **Select PostgreSQL connection type**
4. **Enter credentials** (host, port, database, username, password)
5. **Test connection** and save

#### **Connect SQL clients**

Use any PostgreSQL-compatible SQL client:

* **pgAdmin** - PostgreSQL administration tool
* **DBeaver** - Universal database tool
* **TablePlus** - Modern database client
* **Command line** - `psql` or other CLI tools

Example connection:

```bash theme={null}
psql -h <host> -p <port> -U <username> -d <database>
```

#### **Example SQL queries**

```sql theme={null}
-- Query cube measures and dimensions
SELECT 
  orders.status,
  orders.total_revenue,
  orders.count
FROM orders
WHERE orders.created_at >= '2024-01-01'
GROUP BY orders.status
ORDER BY orders.total_revenue DESC;

-- Time-based analysis
SELECT 
  orders.created_at,
  orders.total_revenue
FROM orders
WHERE orders.created_at >= '2024-01-01'
  AND orders.created_at < '2024-02-01'
GROUP BY orders.created_at
ORDER BY orders.created_at;
```

## REST API credentials

### **Overview**

REST API provides RESTful access for application integration:

* **HTTP-based** - Standard REST interface
* **JSON requests/responses** - Easy integration
* **Token authentication** - Secure API access
* **Flexible querying** - Build queries programmatically

### **Connection components**

**Base URL**

* API endpoint base URL
* Used as prefix for all API requests
* Example: `https://api.example.com/v1`

**Authentication token**

* Bearer token for API authentication
* Include in request headers
* Keep secure and rotate periodically

### **Using REST API credentials**

#### **API request format**

```bash theme={null}
curl -X POST 'https://your-api-url/v1/load' \
  -H 'Authorization: Bearer YOUR_TOKEN' \
  -H 'Content-Type: application/json' \
  -d '{
    "query": {
      "measures": ["orders.total_revenue"],
      "dimensions": ["orders.status"],
      "timeDimensions": [{
        "dimension": "orders.created_at",
        "granularity": "day",
        "dateRange": ["2024-01-01", "2024-01-31"]
      }]
    }
  }'
```

#### **Example queries**

**Simple query:**

```json theme={null}
{
  "query": {
    "measures": ["orders.total_revenue"],
    "dimensions": ["orders.status"]
  }
}
```

**Time-based query:**

```json theme={null}
{
  "query": {
    "measures": ["orders.total_revenue"],
    "timeDimensions": [{
      "dimension": "orders.created_at",
      "granularity": "month"
    }]
  }
}
```

**Filtered query:**

```json theme={null}
{
  "query": {
    "measures": ["orders.total_revenue"],
    "dimensions": ["orders.status"],
    "filters": [{
      "dimension": "orders.status",
      "operator": "equals",
      "values": ["completed"]
    }]
  }
}
```

#### **Integration examples**

**Python:**

```python theme={null}
import requests

url = "https://your-api-url/v1/load"
headers = {
    "Authorization": "Bearer YOUR_TOKEN",
    "Content-Type": "application/json"
}
data = {
    "query": {
        "measures": ["orders.total_revenue"],
        "dimensions": ["orders.status"]
    }
}

response = requests.post(url, json=data, headers=headers)
results = response.json()
```

**JavaScript:**

```javascript theme={null}
const url = 'https://your-api-url/v1/load';
const headers = {
  'Authorization': 'Bearer YOUR_TOKEN',
  'Content-Type': 'application/json'
};
const data = {
  query: {
    measures: ['orders.total_revenue'],
    dimensions: ['orders.status']
  }
};

fetch(url, {
  method: 'POST',
  headers: headers,
  body: JSON.stringify(data)
})
.then(response => response.json())
.then(results => console.log(results));
```

## Server status

### **Status indicator**

The credentials drawer shows server status:

* **🟢 Green** - Server is running and operational
* **🔴 Red** - Server is stopped or unavailable
* **🟡 Yellow** - Server is starting up (PENDING)

### **Server restart**

If schema changes occur, you may need to restart the API server:

1. **Click "Restart" button** in credentials drawer
2. **Wait for restart** - Server will restart and reload schema
3. **Status updates** - Green indicator when ready
4. **Credentials refresh** - May need to refresh credentials after restart

<Note>
  **When to restart**

  Restart the API server when:

  * Schema files are updated and deployed
  * Cube definitions are modified
  * Connection issues occur
  * Server status shows errors
</Note>

## Security best practices

### **Credential management**

<CardGroup cols={2}>
  <Card title="Keep secure" icon="lock">
    **Protect credentials**

    Never share API credentials publicly. Store them securely and use environment variables or secret management tools.
  </Card>

  <Card title="Rotate regularly" icon="sync">
    **Periodic rotation**

    Rotate API credentials periodically to maintain security. Update connected applications when credentials change.
  </Card>

  <Card title="Access control" icon="shield">
    **Limit access**

    Only share credentials with authorized users and applications. Use role-based access control where possible.
  </Card>

  <Card title="Monitor usage" icon="chart-line">
    **Track access**

    Monitor API usage and access patterns to detect unusual activity or potential security issues.
  </Card>
</CardGroup>

### **Connection security**

* **Use HTTPS** - Always use encrypted connections
* **Token expiration** - Configure token expiration policies
* **IP whitelisting** - Restrict access to known IP addresses
* **Rate limiting** - Implement rate limits to prevent abuse
* **Audit logging** - Track API access and usage

## Troubleshooting

### **Common issues**

<AccordionGroup>
  <Accordion icon="key" title="Credentials not showing">
    **Possible causes:**

    * Server heartbeat not RUNNING
    * Project or branch not selected
    * Server not initialized

    **Solutions:**

    * Wait for heartbeat to reach RUNNING status
    * Verify project and branch are selected
    * Check server status indicator
    * Try refreshing the page
  </Accordion>

  <Accordion icon="plug" title="Connection failures">
    **Possible causes:**

    * Incorrect credentials
    * Network connectivity issues
    * Server not running
    * Firewall blocking connections

    **Solutions:**

    * Verify credentials are correct (copy again)
    * Check network connection
    * Verify server status is RUNNING
    * Check firewall and security group settings
    * Test connection from different network
  </Accordion>

  <Accordion icon="exclamation-triangle" title="Authentication errors">
    **Possible causes:**

    * Invalid or expired token
    * Incorrect authorization header
    * Token format issues

    **Solutions:**

    * Verify token is correct and not expired
    * Check authorization header format: `Bearer YOUR_TOKEN`
    * Refresh credentials if token appears invalid
    * Contact support if issues persist
  </Accordion>
</AccordionGroup>

### **Debugging connections**

**Test SQL connection:**

```bash theme={null}
# Test PostgreSQL connection
psql -h <host> -p <port> -U <username> -d <database>

# Or test with connection string
psql "postgresql://username:password@host:port/database"
```

**Test REST API:**

```bash theme={null}
# Test API endpoint
curl -X POST 'https://your-api-url/v1/load' \
  -H 'Authorization: Bearer YOUR_TOKEN' \
  -H 'Content-Type: application/json' \
  -d '{"query": {"measures": ["orders.count"]}}'
```

***

<CardGroup cols={2}>
  <Card title="BI Integration" icon="link" href="/core-features/metric-store/bi-integration">
    **Sync BI tools**

    Learn how to set up automatic synchronization with BI tools.
  </Card>

  <Card title="Cube Playground" icon="code" href="/core-features/metric-store/cube-playground">
    **Build queries**

    Use Cube Playground to build and test queries before connecting external tools.
  </Card>
</CardGroup>
