API Keys API

Manage API keys for authentication

The API Keys API allows you to manage API keys for users and organizations, including creating, listing, and deleting API keys. All endpoints require authentication via API key or OIDC.

Authentication

All endpoints require authentication. You can authenticate using:

  • API Key: Include your API key in the Authorization header: Authorization: Bearer <your-api-key>
  • OIDC: Use OIDC tokens for authentication

Required scopes for different operations:

  • api_key:read: Read API key information and list keys
  • api_key:write: Create and delete API keys

List API keys

Retrieves a list of API keys for a user or organization.

List user API keys

GET /api-keys

Summary

Returns a paginated list of all API keys associated with the authenticated user, including metadata such as name, creation date, expiry, scopes, and access permissions.

Query parameters

ParameterTypeRequiredDescription
organizationstringNoFilter by organization ID (optional)
userstringNoFilter by user ID (optional)
pageintegerNoPage number for pagination (default: 1)
sizeintegerNoNumber of items per page (default: 20, max: 100)

Response

Status: 200 OK

{
  "keys": [
    {
      "id": "key_123",
      "name": "Production API Key",
      "preview": "xata_...",
      "created_at": "2024-01-01T00:00:00Z",
      "created_by": "user_123",
      "created_by_key": null,
      "expiry": "2025-01-01T00:00:00Z",
      "last_used": "2024-01-15T10:30:00Z",
      "scopes": ["read", "write"],
      "projects": ["proj_123"],
      "branches": ["br_123"]
    }
  ],
  "pagination": {
    "page": 1,
    "size": 20,
    "total": 45,
    "pages": 3
  }
}

Response schema

FieldTypeDescription
keysarrayArray of API key objects
paginationobjectPagination information
pagination.pageintegerCurrent page number
pagination.sizeintegerNumber of items per page
pagination.totalintegerTotal number of items
pagination.pagesintegerTotal number of pages
idstringUnique identifier for the API key
namestringHuman-readable name for the API key
previewstringPreview of the API key (first few characters)
created_atstring (date-time)Timestamp when the API key was created
created_bystringID of the user that created this API key
created_by_keystringID of the API key that created this API key
expirystring (date-time)Date when the API key expires (null if no expiry)
last_usedstring (date-time)Timestamp of the last time the key was used
scopesarrayList of scopes granted to this API key
projectsarrayList of project IDs the key has access to
branchesarrayList of branch IDs the key has access to

Create API key

Creates a new API key for a user or organization.

POST /api-keys

Summary

Creates a new API key with specified permissions, scopes, and access restrictions. The full key is only returned once upon creation.

Request body

{
  "name": "New API Key",
  "expiry": "2025-01-01T00:00:00Z",
  "scopes": ["read", "write"],
  "projects": ["proj_123"],
  "branches": ["br_123"]
}

Request body parameters

ParameterTypeRequiredDescription
namestringYesHuman-readable name for the API key
expirystring (date-time)NoOptional expiration date for the API key
scopesarrayYesList of scopes for the API key
projectsarrayNoList of project IDs the key has access to
branchesarrayNoList of branch IDs the key has access to

Response

Status: 201 Created

{
  "id": "key_123",
  "name": "New API Key",
  "key": "xata_live_abc123def456ghi789jkl012mno345pqr678stu901vwx234yz567890",
  "preview": "xata_...",
  "created_at": "2024-01-01T00:00:00Z",
  "created_by": "user_123",
  "created_by_key": null,
  "expiry": "2025-01-01T00:00:00Z",
  "scopes": ["read", "write"],
  "projects": ["proj_123"],
  "branches": ["br_123"]
}

Note: The key field is only returned once upon creation. Store this securely as it cannot be retrieved later.

Response schema

FieldTypeDescription
idstringUnique identifier for the created API key
keystringThe full API key (only returned once)
namestringName of the API key
previewstringPreview of the API key (first few characters)
created_atstring (date-time)Timestamp when the API key was created
created_bystringID of the user that created this API key
created_by_keystringID of the API key that created this API key
expirystring (date-time)Date when the API key expires
scopesarrayList of scopes granted to this API key
projectsarrayList of project IDs the key has access to
branchesarrayList of branch IDs the key has access to

Get API key

Retrieves detailed information about a specific API key.

GET /api-keys/{keyID}

Summary

Returns comprehensive information about an API key including all metadata, permissions, and access details.

Path parameters

ParameterTypeRequiredDescription
keyIDstringYesUnique identifier for the API key

Response

Status: 200 OK

{
  "id": "key_123",
  "name": "Production API Key",
  "preview": "xata_...",
  "created_at": "2024-01-01T00:00:00Z",
  "created_by": "user_123",
  "created_by_key": null,
  "expiry": "2025-01-01T00:00:00Z",
  "last_used": "2024-01-15T10:30:00Z",
  "scopes": ["read", "write"],
  "projects": ["proj_123"],
  "branches": ["br_123"]
}

Response schema

FieldTypeDescription
idstringUnique identifier for the API key
namestringHuman-readable name for the API key
previewstringPreview of the API key (first few characters)
created_atstring (date-time)Timestamp when the API key was created
created_bystringID of the user that created this API key
created_by_keystringID of the API key that created this API key
expirystring (date-time)Date when the API key expires (null if no expiry)
last_usedstring (date-time)Timestamp of the last time the key was used
scopesarrayList of scopes granted to this API key
projectsarrayList of project IDs the key has access to
branchesarrayList of branch IDs the key has access to

Delete API key

Permanently deletes an API key.

DELETE /api-keys/{keyID}

Summary

Permanently removes an API key. This action cannot be undone and will immediately revoke all access for the specified key.

Path parameters

ParameterTypeRequiredDescription
keyIDstringYesUnique identifier for the API key

Response

Status: 204 No Content

No response body is returned on successful deletion.

Error Handling

The API uses standard HTTP status codes and returns error responses in the following format:

{
  "id": "error_identifier",
  "message": "Human-readable error message explaining the issue"
}

Common error responses

StatusError TypeDescription
400GenericErrorRequest was malformed or contained invalid parameters
401AuthorizationErrorAuthentication failed or is missing
403AuthorizationErrorAPI key lacks required scopes for the operation
404GenericErrorRequested API key does not exist
429RateLimitErrorRate limit exceeded
5XXGenericErrorServer error occurred

Error examples

400 Bad Request - Invalid scope

{
  "id": "invalid_scope",
  "message": "Invalid scope 'invalid_scope_name' provided. Valid scopes are: read, write, admin, metrics:read, credentials:read, branch:read, branch:write, project:read, project:write, user:read, user:write, api_key:read, api_key:write"
}

401 Unauthorized - Invalid API key

{
  "id": "invalid_api_key",
  "message": "Invalid or expired API key provided"
}

403 Forbidden - Insufficient scopes

{
  "id": "insufficient_scopes",
  "message": "API key lacks required scope 'api_key:write' for this operation"
}

404 Not Found - API key not found

{
  "id": "api_key_not_found",
  "message": "API key with ID 'key_999' not found"
}

429 Too Many Requests - Rate limit exceeded

{
  "id": "rate_limit_exceeded",
  "message": "Rate limit exceeded. Please try again in 60 seconds"
}

Error resolution guidance

  • 400 Bad Request: Check request body format and parameter values
  • 401 Unauthorized: Verify API key is valid and has required scopes
  • 403 Forbidden: Ensure your API key has the necessary scopes for the operation
  • 404 Not Found: Confirm API key ID is correct
  • 429 Too Many Requests: Wait for the rate limit window to reset or implement exponential backoff
  • 5XX Server Error: Retry the request or contact support if persistent

Rate Limiting

API requests are subject to rate limiting. The current limits are:

  • 100 requests per minute per API key
  • 1000 requests per hour per API key

Rate limit headers are included in all responses:

  • X-RateLimit-Limit: The maximum number of requests allowed per time window
  • X-RateLimit-Remaining: The number of requests remaining in the current time window
  • X-RateLimit-Reset: The time when the current rate limit window resets (Unix timestamp)

When rate limits are exceeded, the API returns a 429 Too Many Requests status with appropriate error details.

Schema Reference

Core Data Models

APIKeyPreview

Basic API key information returned when listing keys.

FieldTypeRequiredDescription
idstringYesUnique identifier for the API key
namestringYesHuman-readable name for the API key
previewstringYesPreview of the API key (first few characters)
created_atstring (date-time)YesTimestamp when the API key was created
expirystring (date-time)YesDate when the API key expires (null if no expiry)
last_usedstring (date-time)YesTimestamp of the last time the key was used
scopesarrayYesList of scopes granted to this API key
projectsarrayYesList of project IDs the key has access to
branchesarrayYesList of branch IDs the key has access to
created_bystringNoID of the user that created this API key
created_by_keystringNoID of the API key that created this API key

APIKeyCreationRequest

Request body for creating a new API key.

FieldTypeRequiredDescription
namestringYesHuman-readable name for the API key
expirystring (date-time)NoOptional expiration date for the API key
scopesarrayYesList of scopes for the API key
projectsarrayNoList of project IDs the key has access to
branchesarrayNoList of branch IDs the key has access to

APIKey

Complete API key information including all metadata and permissions.

FieldTypeRequiredDescription
idstringYesUnique identifier for the API key
namestringYesHuman-readable name for the API key
previewstringYesPreview of the API key (first few characters)
created_atstring (date-time)YesTimestamp when the API key was created
expirystring (date-time)YesDate when the API key expires (null if no expiry)
last_usedstring (date-time)YesTimestamp of the last time the key was used
scopesarrayYesList of scopes granted to this API key
projectsarrayYesList of project IDs the key has access to
branchesarrayYesList of branch IDs the key has access to
created_bystringNoID of the user that created this API key
created_by_keystringNoID of the API key that created this API key

PaginationInfo

Pagination metadata for list responses.

FieldTypeRequiredDescription
pageintegerYesCurrent page number
sizeintegerYesNumber of items per page
totalintegerYesTotal number of items
pagesintegerYesTotal number of pages

Scopes

API keys can have the following scopes that control access to different resources and operations:

Data Access Scopes

  • read: Read access to database records and metadata
  • write: Write access to create, update, and delete database records
  • admin: Full administrative access to all resources

Monitoring and Metrics

  • metrics:read: Access to performance metrics, query statistics, and monitoring data

Infrastructure Access

  • credentials:read: Access to database connection credentials and connection strings
  • branch:read: Read access to branch information and configuration
  • branch:write: Write access to create, update, and delete branches
  • project:read: Read access to project information and settings
  • project:write: Write access to create, update, and delete projects

User Management

  • user:read: Read access to user information and profiles
  • user:write: Write access to create, update, and delete users

API Key Management

  • api_key:read: Read access to API key information and list keys
  • api_key:write: Write access to create and delete API keys

Scope Combinations

Common scope combinations for different use cases:

  • Read-only access: ["read"]
  • Full database access: ["read", "write"]
  • Developer access: ["read", "write", "branch:read", "project:read"]
  • Admin access: ["admin"]
  • Monitoring access: ["metrics:read", "credentials:read"]

Best Practices

Security

  • Store API keys securely and never commit them to version control
  • Use environment variables or secure secret management systems
  • Rotate API keys regularly, especially for production environments
  • Set appropriate expiry dates for temporary or testing keys
  • Use the principle of least privilege - only grant necessary scopes

Key Management

  • Use descriptive names for API keys to easily identify their purpose
  • Create separate keys for different environments (development, staging, production)
  • Monitor key usage and set up alerts for unusual activity
  • Regularly audit and clean up unused or expired keys

Rate Limiting

  • Implement exponential backoff when hitting rate limits
  • Cache responses when possible to reduce API calls
  • Monitor rate limit headers to optimize request patterns
  • Consider implementing request queuing for high-volume operations

Error Handling

  • Always check HTTP status codes and handle errors gracefully
  • Implement retry logic with exponential backoff for transient errors
  • Log error details for debugging and monitoring
  • Provide user-friendly error messages in your applications