# API Tokens Source: https://docs.apitraffic.io/api-reference/api-tokens Manage API tokens for programmatic access to your ApiTraffic account ## List API Tokens Retrieve all API tokens associated with an account. ### Path Parameters Account identifier (format: `acc_` followed by 27 alphanumeric characters) ### Headers Bearer token for authentication ### Response Indicates if there are more records to paginate through Unique API token identifier Account identifier this token belongs to Name of the API token Description of the token's purpose Array of permission scopes granted to this token ISO 8601 timestamp of last token usage (nullable) ISO 8601 timestamp when token expires (nullable for no expiration) Whether this token is currently active ISO 8601 timestamp of token creation ```bash cURL theme={null} curl -X GET "https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/apiTokens" \ -H "Authorization: Bearer your-jwt-token" ``` ```javascript Node.js theme={null} const response = await fetch('https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/apiTokens', { headers: { 'Authorization': 'Bearer your-jwt-token' } }); const tokens = await response.json(); console.log(tokens); ``` ```python Python theme={null} import requests response = requests.get( 'https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/apiTokens', headers={'Authorization': 'Bearer your-jwt-token'} ) tokens = response.json() print(tokens) ``` ```json Response theme={null} { "hasMore": false, "records": [ { "sid": "tok_abc123def456ghi789jkl012", "accountSid": "acc_abc123def456ghi789jkl012", "name": "Production API Token", "description": "Token for production monitoring integration", "scopes": ["buckets:read", "requests:read", "metrics:read"], "lastUsedAt": "2023-12-01T14:30:00.000Z", "expiresAt": "2024-12-01T00:00:00.000Z", "isActive": true, "createdAt": "2023-12-01T10:30:00.000Z" }, { "sid": "tok_xyz789uvw012rst345abc", "accountSid": "acc_abc123def456ghi789jkl012", "name": "CI/CD Token", "description": "Token for automated testing and deployment", "scopes": ["buckets:read", "buckets:write"], "lastUsedAt": null, "expiresAt": null, "isActive": true, "createdAt": "2023-11-15T09:15:00.000Z" } ] } ``` *** ## Get API Token Retrieve details of a specific API token. ### Path Parameters Account identifier API token identifier ### Headers Bearer token for authentication ### Response Returns a single API token object with the same structure as described in the List API Tokens response. ```bash cURL theme={null} curl -X GET "https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/apiTokens/tok_abc123def456ghi789jkl012" \ -H "Authorization: Bearer your-jwt-token" ``` ```javascript Node.js theme={null} const response = await fetch('https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/apiTokens/tok_abc123def456ghi789jkl012', { headers: { 'Authorization': 'Bearer your-jwt-token' } }); const token = await response.json(); console.log(token); ``` ```json Response theme={null} { "sid": "tok_abc123def456ghi789jkl012", "accountSid": "acc_abc123def456ghi789jkl012", "name": "Production API Token", "description": "Token for production monitoring integration", "scopes": ["buckets:read", "requests:read", "metrics:read"], "lastUsedAt": "2023-12-01T14:30:00.000Z", "expiresAt": "2024-12-01T00:00:00.000Z", "isActive": true, "createdAt": "2023-12-01T10:30:00.000Z" } ``` *** ## Create API Token Create a new API token for programmatic access. ### Path Parameters Account identifier ### Headers Bearer token for authentication ### Request Body Name of the API token Description of the token's purpose Array of permission scopes to grant to this token ISO 8601 timestamp when token should expire (optional, null for no expiration) ### Response Unique API token identifier The actual API token value (only returned on creation) Account identifier Name of the API token Description of the token Array of granted permission scopes Expiration timestamp (nullable) Whether the token is active ISO 8601 timestamp of creation The token value is only returned once during creation. Store it securely as it cannot be retrieved again. ```bash cURL theme={null} curl -X POST "https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/apiTokens" \ -H "Authorization: Bearer your-jwt-token" \ -H "Content-Type: application/json" \ -d '{ "name": "Analytics Token", "description": "Token for analytics dashboard integration", "scopes": ["metrics:read", "buckets:read"], "expiresAt": "2024-12-31T23:59:59.000Z" }' ``` ```javascript Node.js theme={null} const response = await fetch('https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/apiTokens', { method: 'POST', headers: { 'Authorization': 'Bearer your-jwt-token', 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'Analytics Token', description: 'Token for analytics dashboard integration', scopes: ['metrics:read', 'buckets:read'], expiresAt: '2024-12-31T23:59:59.000Z' }) }); const token = await response.json(); console.log(token); // Store token.token securely! ``` ```python Python theme={null} import requests response = requests.post( 'https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/apiTokens', headers={ 'Authorization': 'Bearer your-jwt-token', 'Content-Type': 'application/json' }, json={ 'name': 'Analytics Token', 'description': 'Token for analytics dashboard integration', 'scopes': ['metrics:read', 'buckets:read'], 'expiresAt': '2024-12-31T23:59:59.000Z' } ) token = response.json() print(token) # Store token['token'] securely! ``` ```json Response theme={null} { "sid": "tok_new789uvw012rst345def", "token": "at_live_1234567890abcdef...", "accountSid": "acc_abc123def456ghi789jkl012", "name": "Analytics Token", "description": "Token for analytics dashboard integration", "scopes": ["metrics:read", "buckets:read"], "expiresAt": "2024-12-31T23:59:59.000Z", "isActive": true, "createdAt": "2023-12-01T15:45:00.000Z" } ``` *** ## Update API Token Update an existing API token's metadata. You cannot update the token value itself or its scopes. To change scopes, create a new token and delete the old one. ### Path Parameters Account identifier API token identifier ### Headers Bearer token for authentication ### Request Body Name of the API token Description of the token's purpose Whether this token should be active ### Response Returns the updated API token object (without the token value). ```bash cURL theme={null} curl -X PUT "https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/apiTokens/tok_abc123def456ghi789jkl012" \ -H "Authorization: Bearer your-jwt-token" \ -H "Content-Type: application/json" \ -d '{ "name": "Updated Production Token", "description": "Updated description for production monitoring", "isActive": false }' ``` ```javascript Node.js theme={null} const response = await fetch('https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/apiTokens/tok_abc123def456ghi789jkl012', { method: 'PUT', headers: { 'Authorization': 'Bearer your-jwt-token', 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'Updated Production Token', description: 'Updated description for production monitoring', isActive: false }) }); const token = await response.json(); console.log(token); ``` ```json Response theme={null} { "sid": "tok_abc123def456ghi789jkl012", "accountSid": "acc_abc123def456ghi789jkl012", "name": "Updated Production Token", "description": "Updated description for production monitoring", "scopes": ["buckets:read", "requests:read", "metrics:read"], "lastUsedAt": "2023-12-01T14:30:00.000Z", "expiresAt": "2024-12-01T00:00:00.000Z", "isActive": false, "createdAt": "2023-12-01T10:30:00.000Z" } ``` *** ## Delete API Token Delete an API token, immediately revoking access. This action is irreversible. Any applications using this token will immediately lose access. ### Path Parameters Account identifier API token identifier ### Headers Bearer token for authentication ### Response ID of the deleted API token Flag indicating the token was successfully deleted ```bash cURL theme={null} curl -X DELETE "https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/apiTokens/tok_abc123def456ghi789jkl012" \ -H "Authorization: Bearer your-jwt-token" ``` ```javascript Node.js theme={null} const response = await fetch('https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/apiTokens/tok_abc123def456ghi789jkl012', { method: 'DELETE', headers: { 'Authorization': 'Bearer your-jwt-token' } }); const result = await response.json(); console.log(result); ``` ```json Response theme={null} { "sid": "tok_abc123def456ghi789jkl012", "deleted": true } ``` *** ## Available Scopes API tokens can be granted specific scopes to limit their access: ### Bucket Scopes * `buckets:read` - View bucket information * `buckets:write` - Create and modify buckets * `buckets:delete` - Delete buckets ### Request Scopes * `requests:read` - View request data * `requests:write` - Modify request metadata (notes, etc.) * `requests:delete` - Delete individual requests ### Metrics Scopes * `metrics:read` - Access analytics and metrics data ### Redaction Scopes * `redactions:read` - View redaction rules * `redactions:write` - Create and modify redaction rules * `redactions:delete` - Delete redaction rules ### Exclusion Scopes * `exclusions:read` - View exclusion rules * `exclusions:write` - Create and modify exclusion rules * `exclusions:delete` - Delete exclusion rules ### Workflow Scopes * `workflows:read` - View workflow configurations * `workflows:write` - Create and modify workflows * `workflows:delete` - Delete workflows ### Token Management Scopes * `tokens:read` - View API token information * `tokens:write` - Create and modify API tokens * `tokens:delete` - Delete API tokens *** ## Using API Tokens Once created, use your API token in the `Authorization` header: ```bash theme={null} curl -H "Authorization: Bearer at_live_1234567890abcdef..." \ https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/buckets ``` ### Token Format * **Live tokens**: `at_live_` followed by random characters * **Test tokens**: `at_test_` followed by random characters ### Best Practices 1. **Principle of Least Privilege**: Only grant the minimum scopes required 2. **Regular Rotation**: Rotate tokens periodically for security 3. **Secure Storage**: Store tokens securely, never in plain text 4. **Monitor Usage**: Check `lastUsedAt` to identify unused tokens 5. **Set Expiration**: Use expiration dates for temporary access 6. **Environment Separation**: Use different tokens for different environments # Authentication Source: https://docs.apitraffic.io/api-reference/authentication Authentication endpoints for user management and session handling ## Get User Profile Returns the authenticated user's profile information including account details. ### Headers Bearer token for authentication ### Response User's unique identifier User's first name User's last name User's email address User's timezone setting Default account identifier ISO 8601 timestamp of user creation Array of account objects the user has access to Hash for secure chat integration ```bash cURL theme={null} curl -X GET "https://api.apitraffic.io/v1/authentication/me" \ -H "Authorization: Bearer your-jwt-token" ``` ```javascript Node.js theme={null} const response = await fetch('https://api.apitraffic.io/v1/authentication/me', { headers: { 'Authorization': 'Bearer your-jwt-token' } }); const user = await response.json(); console.log(user); ``` ```python Python theme={null} import requests response = requests.get( 'https://api.apitraffic.io/v1/authentication/me', headers={'Authorization': 'Bearer your-jwt-token'} ) user = response.json() print(user) ``` ```json Response theme={null} { "sid": "usr_abc123def456ghi789", "firstName": "John", "lastName": "Doe", "email": "john.doe@example.com", "timezone": "America/New_York", "defaultAccountSid": "acc_xyz789uvw012rst345", "createdAt": "2023-12-01T10:30:00.000Z", "accounts": [ { "sid": "acc_xyz789uvw012rst345", "name": "My Company", "role": "owner" } ], "chat": { "userHash": "a1b2c3d4e5f6g7h8i9j0" } } ``` *** ## Verify Token Verifies the validity of an authentication token. ### Headers Bearer token to verify ### Response Account identifier associated with the token ```bash cURL theme={null} curl -X GET "https://api.apitraffic.io/v1/authentication/verify" \ -H "Authorization: Bearer your-jwt-token" ``` ```javascript Node.js theme={null} const response = await fetch('https://api.apitraffic.io/v1/authentication/verify', { headers: { 'Authorization': 'Bearer your-jwt-token' } }); const verification = await response.json(); console.log(verification); ``` ```json Response theme={null} { "accountSid": "acc_xyz789uvw012rst345" } ``` *** ## Sign Out Signs the user out of their current session. ### Headers Bearer token for the session to terminate ### Response Indicates if the sign out was successful ```bash cURL theme={null} curl -X GET "https://api.apitraffic.io/v1/authentication/signout" \ -H "Authorization: Bearer your-jwt-token" ``` ```javascript Node.js theme={null} const response = await fetch('https://api.apitraffic.io/v1/authentication/signout', { headers: { 'Authorization': 'Bearer your-jwt-token' } }); const result = await response.json(); console.log(result); ``` ```json Response theme={null} { "success": true } ``` # Buckets Source: https://docs.apitraffic.io/api-reference/buckets Manage buckets for organizing your API traffic data ## List Buckets Retrieve all buckets associated with an account. ### Path Parameters Account identifier (format: `acc_` followed by 27 alphanumeric characters) ### Headers Bearer token for authentication ### Response Indicates if there are more records to paginate through Unique bucket identifier Account identifier this bucket belongs to Name of the bucket Whether SSL certificates should be verified as valid and trusted Whether the bucket is connected to an application via the SDK ISO 8601 timestamp of bucket creation ```bash cURL theme={null} curl -X GET "https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/buckets" \ -H "Authorization: Bearer your-jwt-token" ``` ```javascript Node.js theme={null} const response = await fetch('https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/buckets', { headers: { 'Authorization': 'Bearer your-jwt-token' } }); const buckets = await response.json(); console.log(buckets); ``` ```python Python theme={null} import requests response = requests.get( 'https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/buckets', headers={'Authorization': 'Bearer your-jwt-token'} ) buckets = response.json() print(buckets) ``` ```json Response theme={null} { "hasMore": false, "records": [ { "sid": "bkt_xyz789uvw012rst345abc", "accountSid": "acc_abc123def456ghi789jkl012", "name": "Production API", "verifySslCerts": true, "appIsConnected": true, "createdAt": "2023-12-01T10:30:00.000Z" } ] } ``` *** ## Get Bucket Retrieve details of a specific bucket. ### Path Parameters Account identifier Bucket identifier ### Headers Bearer token for authentication ### Response Unique bucket identifier Account identifier this bucket belongs to Name of the bucket Whether SSL certificates should be verified as valid and trusted Whether the bucket is connected to an application via the SDK ISO 8601 timestamp of bucket creation ```bash cURL theme={null} curl -X GET "https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/buckets/bkt_xyz789uvw012rst345abc" \ -H "Authorization: Bearer your-jwt-token" ``` ```javascript Node.js theme={null} const response = await fetch('https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/buckets/bkt_xyz789uvw012rst345abc', { headers: { 'Authorization': 'Bearer your-jwt-token' } }); const bucket = await response.json(); console.log(bucket); ``` ```json Response theme={null} { "sid": "bkt_xyz789uvw012rst345abc", "accountSid": "acc_abc123def456ghi789jkl012", "name": "Production API", "verifySslCerts": true, "appIsConnected": true, "createdAt": "2023-12-01T10:30:00.000Z" } ``` *** ## Create Bucket Create a new bucket for organizing API traffic data. ### Path Parameters Account identifier ### Headers Bearer token for authentication ### Request Body The name of the bucket ### Response Returns the created bucket object with the same structure as the Get Bucket response. ```bash cURL theme={null} curl -X POST "https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/buckets" \ -H "Authorization: Bearer your-jwt-token" \ -H "Content-Type: application/json" \ -d '{ "name": "Staging API" }' ``` ```javascript Node.js theme={null} const response = await fetch('https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/buckets', { method: 'POST', headers: { 'Authorization': 'Bearer your-jwt-token', 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'Staging API' }) }); const bucket = await response.json(); console.log(bucket); ``` ```python Python theme={null} import requests response = requests.post( 'https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/buckets', headers={ 'Authorization': 'Bearer your-jwt-token', 'Content-Type': 'application/json' }, json={'name': 'Staging API'} ) bucket = response.json() print(bucket) ``` ```json Response theme={null} { "sid": "bkt_new789uvw012rst345def", "accountSid": "acc_abc123def456ghi789jkl012", "name": "Staging API", "verifySslCerts": true, "appIsConnected": false, "createdAt": "2023-12-01T15:45:00.000Z" } ``` *** ## Update Bucket Update the details of an existing bucket. ### Path Parameters Account identifier Bucket identifier ### Headers Bearer token for authentication ### Request Body The name of the bucket Whether SSL certificates should be verified as valid and trusted ### Response Returns the updated bucket object. ```bash cURL theme={null} curl -X PUT "https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/buckets/bkt_xyz789uvw012rst345abc" \ -H "Authorization: Bearer your-jwt-token" \ -H "Content-Type: application/json" \ -d '{ "name": "Updated Production API", "verifySslCerts": false }' ``` ```javascript Node.js theme={null} const response = await fetch('https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/buckets/bkt_xyz789uvw012rst345abc', { method: 'PUT', headers: { 'Authorization': 'Bearer your-jwt-token', 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'Updated Production API', verifySslCerts: false }) }); const bucket = await response.json(); console.log(bucket); ``` ```json Response theme={null} { "sid": "bkt_xyz789uvw012rst345abc", "accountSid": "acc_abc123def456ghi789jkl012", "name": "Updated Production API", "verifySslCerts": false, "appIsConnected": true, "createdAt": "2023-12-01T10:30:00.000Z" } ``` *** ## Delete Bucket Delete a bucket and all associated requests. This action is irreversible. All data associated with the bucket will be permanently deleted. ### Path Parameters Account identifier Bucket identifier ### Headers Bearer token for authentication ### Response ID of the deleted bucket Flag indicating the bucket was successfully deleted ```bash cURL theme={null} curl -X DELETE "https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/buckets/bkt_xyz789uvw012rst345abc" \ -H "Authorization: Bearer your-jwt-token" ``` ```javascript Node.js theme={null} const response = await fetch('https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/buckets/bkt_xyz789uvw012rst345abc', { method: 'DELETE', headers: { 'Authorization': 'Bearer your-jwt-token' } }); const result = await response.json(); console.log(result); ``` ```json Response theme={null} { "sid": "bkt_xyz789uvw012rst345abc", "deleted": true } ``` *** ## Get SDK Settings Retrieve SDK settings for a bucket based on the ingestion key. ### Path Parameters Bucket identifier ### Query Parameters Where data should be redacted. Must be either `client` or `server` ID of the client attempting to get the SDK settings ### Headers Bearer token for authentication ### Response Returns SDK configuration settings including redaction rules and exclusion patterns. ```bash cURL theme={null} curl -X GET "https://api.apitraffic.io/v1/buckets/bkt_xyz789uvw012rst345abc/sdk?redactAt=client&clientId=client_123" \ -H "Authorization: Bearer your-jwt-token" ``` ```javascript Node.js theme={null} const response = await fetch('https://api.apitraffic.io/v1/buckets/bkt_xyz789uvw012rst345abc/sdk?redactAt=client&clientId=client_123', { headers: { 'Authorization': 'Bearer your-jwt-token' } }); const settings = await response.json(); console.log(settings); ``` ```json Response theme={null} { "redactionRules": [ { "field": "password", "action": "redact" } ], "exclusionRules": [ { "path": "/health", "method": "GET" } ], "settings": { "interceptOutbound": true, "debug": false } } ``` # Events Source: https://docs.apitraffic.io/api-reference/events Track deployments, incidents, and other markers to correlate with your API traffic Events allow you to mark significant moments — deployments, incidents, configuration changes, scaling events — directly on your ApiTraffic dashboard charts. This makes it easy to correlate changes in error rates, latencies, and throughput with specific actions in your infrastructure. ## How Events Work When you create an event, it appears as a vertical annotation on your Throughput and Response Time dashboard charts. This lets you visually answer questions like: * "Did error rates spike after that deploy?" * "Did response times improve after we scaled up?" * "When exactly did that incident start?" ### Event Types | Type | Description | | --------------- | ------------------------------------------- | | `deployment` | Code releases, deploys, rollbacks | | `incident` | Outages, degradations, alerts fired | | `config_change` | Feature flags, environment variable changes | | `scale` | Autoscaling events, manual scaling | | `custom` | Anything else you want to track | ### Scoping Events can be scoped to specific **buckets** and/or **environments**, or applied globally: * **`["*"]`** (default) — applies to all buckets or all environments * **Specific SIDs** — e.g. `["bkt_abc123"]` to scope to a single bucket Events scoped to a bucket will only appear on that bucket's dashboard. Events scoped to `["*"]` appear everywhere. ## Creating Events There are three ways to create events: ### 1. Dashboard UI Navigate to **Account → Events** and click **Create Event**. Fill in the type, name, description, and optionally scope to specific buckets and environments. ### 2. REST API Send a `POST` request to create events programmatically — ideal for CI/CD pipelines. ### 3. MCP Server If you have an MCP token configured, AI assistants can create events using the `create_event` tool. *** ## CI/CD Integration Examples The most powerful use of events is automated creation from your CI/CD pipeline. Here are examples for common platforms: ```yaml GitHub Actions theme={null} # Add to the end of your deploy job - name: Create ApiTraffic Deploy Event run: | curl -X POST "https://api.apitraffic.io/v1/accounts/${{ secrets.APITRAFFIC_ACCOUNT_SID }}/events" \ -H "Authorization: Bearer ${{ secrets.APITRAFFIC_API_TOKEN }}" \ -H "Content-Type: application/json" \ -d '{ "type": "deployment", "name": "${{ github.ref_name }} deploy", "description": "Commit: ${{ github.sha }}", "source": "github_actions", "metadata": { "commitSha": "${{ github.sha }}", "branch": "${{ github.ref_name }}", "actor": "${{ github.actor }}", "runId": "${{ github.run_id }}" } }' ``` ```yaml GitLab CI theme={null} # Add to your deploy stage create_event: stage: deploy script: - | curl -X POST "https://api.apitraffic.io/v1/accounts/${APITRAFFIC_ACCOUNT_SID}/events" \ -H "Authorization: Bearer ${APITRAFFIC_API_TOKEN}" \ -H "Content-Type: application/json" \ -d "{ \"type\": \"deployment\", \"name\": \"${CI_COMMIT_TAG:-$CI_COMMIT_SHORT_SHA} deploy\", \"description\": \"Pipeline: ${CI_PIPELINE_ID}\", \"source\": \"gitlab_ci\", \"metadata\": { \"commitSha\": \"${CI_COMMIT_SHA}\", \"branch\": \"${CI_COMMIT_BRANCH}\", \"pipelineId\": \"${CI_PIPELINE_ID}\" } }" ``` ```groovy Jenkins theme={null} // Add to the end of your Jenkinsfile post { success { sh """ curl -X POST "https://api.apitraffic.io/v1/accounts/\${APITRAFFIC_ACCOUNT_SID}/events" \ -H "Authorization: Bearer \${APITRAFFIC_API_TOKEN}" \ -H "Content-Type: application/json" \ -d '{ "type": "deployment", "name": "${env.BUILD_TAG} deploy", "source": "jenkins", "metadata": { "buildNumber": "${env.BUILD_NUMBER}", "jobName": "${env.JOB_NAME}" } }' """ } } ``` *** ## List Events Retrieve events for an account, with optional filtering by type, time range, and bucket. ### Path Parameters Account identifier (format: `acc_` followed by 27 alphanumeric characters) ### Query Parameters Filter by event type: `deployment`, `incident`, `config_change`, `scale`, `custom` ISO 8601 start time to filter events from ISO 8601 end time to filter events until Filter to events that apply to a specific bucket Filter to events that apply to a specific environment Maximum number of results (default: 25, max: 100) ### Headers Bearer token for authentication ### Response Indicates if there are more records to paginate through Unique event identifier Account identifier this event belongs to Event type: `deployment`, `incident`, `config_change`, `scale`, `custom` Human-readable event name Longer description of the event (nullable) Source of the event, e.g. `github_actions`, `jenkins`, `manual` (nullable) Freeform key/value metadata (nullable) Bucket SIDs this event applies to. `["*"]` means all buckets. Environment SIDs this event applies to. `["*"]` means all environments. ISO 8601 timestamp when the event started ISO 8601 timestamp when the event ended (nullable for point-in-time events) ISO 8601 timestamp of event creation ```bash cURL theme={null} curl -X GET "https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/events?type=deployment&limit=10" \ -H "Authorization: Bearer your-jwt-token" ``` ```javascript Node.js theme={null} const response = await fetch('https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/events?type=deployment&limit=10', { headers: { 'Authorization': 'Bearer your-jwt-token' } }); const events = await response.json(); console.log(events); ``` ```python Python theme={null} import requests response = requests.get( 'https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/events', headers={'Authorization': 'Bearer your-jwt-token'}, params={'type': 'deployment', 'limit': 10} ) events = response.json() print(events) ``` ```json Response theme={null} { "hasMore": false, "records": [ { "sid": "evt_abc123def456ghi789jkl012", "accountSid": "acc_abc123def456ghi789jkl012", "type": "deployment", "name": "v2.3.1 production release", "description": "Commit: a1b2c3d4", "source": "github_actions", "metadata": { "commitSha": "a1b2c3d4e5f6", "branch": "main", "actor": "jsmith" }, "bucketSids": ["*"], "environmentSids": ["*"], "startedAt": "2024-01-15T14:30:00.000Z", "endedAt": null, "createdAt": "2024-01-15T14:30:05.000Z" } ] } ``` *** ## Get Event Retrieve details of a specific event. ### Path Parameters Account identifier Event identifier ### Headers Bearer token for authentication ### Response Returns a single event object with the same structure as described in the List Events response. ```bash cURL theme={null} curl -X GET "https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/events/evt_abc123def456ghi789jkl012" \ -H "Authorization: Bearer your-jwt-token" ``` ```javascript Node.js theme={null} const response = await fetch('https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/events/evt_abc123def456ghi789jkl012', { headers: { 'Authorization': 'Bearer your-jwt-token' } }); const event = await response.json(); console.log(event); ``` ```json Response theme={null} { "sid": "evt_abc123def456ghi789jkl012", "accountSid": "acc_abc123def456ghi789jkl012", "type": "deployment", "name": "v2.3.1 production release", "description": "Commit: a1b2c3d4", "source": "github_actions", "metadata": { "commitSha": "a1b2c3d4e5f6", "branch": "main" }, "bucketSids": ["*"], "environmentSids": ["*"], "startedAt": "2024-01-15T14:30:00.000Z", "endedAt": null, "createdAt": "2024-01-15T14:30:05.000Z" } ``` *** ## Create Event Create a new event marker. ### Path Parameters Account identifier ### Headers Bearer token for authentication ### Request Body Event type: `deployment`, `incident`, `config_change`, `scale`, `custom` Human-readable event name (e.g. "v2.3.1 production release") Longer description of the event Source of the event (e.g. `github_actions`, `gitlab_ci`, `jenkins`, `manual`) Freeform key/value metadata. Use this to store commit SHAs, branch names, image tags, or any other context. Bucket SIDs this event applies to. Defaults to `["*"]` (all buckets). Environment SIDs this event applies to. Defaults to `["*"]` (all environments). ISO 8601 timestamp when the event started. Defaults to the current time. ISO 8601 timestamp when the event ended. Leave null for point-in-time events (e.g. a deploy). ### Response Returns the created event object. ```bash cURL theme={null} curl -X POST "https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/events" \ -H "Authorization: Bearer your-jwt-token" \ -H "Content-Type: application/json" \ -d '{ "type": "deployment", "name": "v2.3.1 production release", "description": "Deployed from main branch", "source": "github_actions", "metadata": { "commitSha": "a1b2c3d4e5f6", "branch": "main", "imageTag": "v2.3.1" } }' ``` ```javascript Node.js theme={null} const response = await fetch('https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/events', { method: 'POST', headers: { 'Authorization': 'Bearer your-jwt-token', 'Content-Type': 'application/json' }, body: JSON.stringify({ type: 'deployment', name: 'v2.3.1 production release', description: 'Deployed from main branch', source: 'github_actions', metadata: { commitSha: 'a1b2c3d4e5f6', branch: 'main', imageTag: 'v2.3.1' } }) }); const event = await response.json(); console.log(event); ``` ```python Python theme={null} import requests response = requests.post( 'https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/events', headers={ 'Authorization': 'Bearer your-jwt-token', 'Content-Type': 'application/json' }, json={ 'type': 'deployment', 'name': 'v2.3.1 production release', 'description': 'Deployed from main branch', 'source': 'github_actions', 'metadata': { 'commitSha': 'a1b2c3d4e5f6', 'branch': 'main', 'imageTag': 'v2.3.1' } } ) event = response.json() print(event) ``` ```json Response theme={null} { "sid": "evt_new789uvw012rst345def", "accountSid": "acc_abc123def456ghi789jkl012", "type": "deployment", "name": "v2.3.1 production release", "description": "Deployed from main branch", "source": "github_actions", "metadata": { "commitSha": "a1b2c3d4e5f6", "branch": "main", "imageTag": "v2.3.1" }, "bucketSids": ["*"], "environmentSids": ["*"], "startedAt": "2024-01-15T14:30:00.000Z", "endedAt": null, "createdAt": "2024-01-15T14:30:05.000Z" } ``` *** ## Update Event Update an existing event. Useful for setting the `endedAt` time on an incident or updating metadata. ### Path Parameters Account identifier Event identifier ### Headers Bearer token for authentication ### Request Body All fields from the Create Event request body are accepted. Only provided fields will be updated. ### Response Returns the updated event object. ```bash cURL theme={null} curl -X PUT "https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/events/evt_abc123def456ghi789jkl012" \ -H "Authorization: Bearer your-jwt-token" \ -H "Content-Type: application/json" \ -d '{ "endedAt": "2024-01-15T15:00:00.000Z", "description": "Incident resolved - root cause was database connection pool exhaustion" }' ``` ```javascript Node.js theme={null} const response = await fetch('https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/events/evt_abc123def456ghi789jkl012', { method: 'PUT', headers: { 'Authorization': 'Bearer your-jwt-token', 'Content-Type': 'application/json' }, body: JSON.stringify({ endedAt: '2024-01-15T15:00:00.000Z', description: 'Incident resolved - root cause was database connection pool exhaustion' }) }); const event = await response.json(); console.log(event); ``` ```json Response theme={null} { "sid": "evt_abc123def456ghi789jkl012", "accountSid": "acc_abc123def456ghi789jkl012", "type": "incident", "name": "Database connection spike", "description": "Incident resolved - root cause was database connection pool exhaustion", "source": "manual", "metadata": null, "bucketSids": ["*"], "environmentSids": ["*"], "startedAt": "2024-01-15T14:00:00.000Z", "endedAt": "2024-01-15T15:00:00.000Z", "createdAt": "2024-01-15T14:05:00.000Z" } ``` *** ## Delete Event Delete an event marker. ### Path Parameters Account identifier Event identifier ### Headers Bearer token for authentication ### Response ID of the deleted event Flag indicating the event was successfully deleted ```bash cURL theme={null} curl -X DELETE "https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/events/evt_abc123def456ghi789jkl012" \ -H "Authorization: Bearer your-jwt-token" ``` ```javascript Node.js theme={null} const response = await fetch('https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/events/evt_abc123def456ghi789jkl012', { method: 'DELETE', headers: { 'Authorization': 'Bearer your-jwt-token' } }); const result = await response.json(); console.log(result); ``` ```json Response theme={null} { "sid": "evt_abc123def456ghi789jkl012", "deleted": true } ``` *** ## MCP Server Access Events are also accessible through the ApiTraffic MCP server, allowing AI assistants to create and list events: | Tool | Description | | -------------- | ----------------------------------------------------------------- | | `list_events` | List event markers with filtering by type, time range, and bucket | | `create_event` | Create a new event marker | To use MCP tools, you need an MCP token configured in your account. See [MCP Tokens](/api-reference/mcp-tokens) for setup instructions. ## Best Practices **Automate event creation** — The most valuable events are created automatically by your CI/CD pipeline. Add a deploy event step to every release workflow so you never miss a correlation. * **Use descriptive names** — Include version numbers, branch names, or ticket IDs in event names so they're meaningful at a glance on the chart. * **Add metadata** — Store commit SHAs, Docker image tags, PR numbers, and other context in the `metadata` field. This makes it easy to trace back from a traffic anomaly to the exact change. * **Scope when possible** — If a deploy only affects one service/bucket, scope the event to that bucket. This keeps dashboards clean and focused. * **Close incidents** — When an incident is resolved, update the event with an `endedAt` timestamp and a description of the resolution. * **Use consistent sources** — Standardize on source names like `github_actions`, `gitlab_ci`, `jenkins`, `manual` across your team. # Exclusions Source: https://docs.apitraffic.io/api-reference/exclusions Manage request exclusion rules to filter out unwanted traffic ## List Exclusions Retrieve all exclusion rules configured for an account. ### Path Parameters Account identifier (format: `acc_` followed by 27 alphanumeric characters) ### Headers Bearer token for authentication ### Response Indicates if there are more records to paginate through Unique exclusion rule identifier Account identifier this exclusion belongs to Name of the exclusion rule Description of what this rule excludes URL path pattern to match (supports wildcards) HTTP method to match (GET, POST, PUT, DELETE, etc.) or \* for all HTTP status code to match (nullable, null means all status codes) Whether this exclusion rule is currently active ISO 8601 timestamp of rule creation ```bash cURL theme={null} curl -X GET "https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/exclusions" \ -H "Authorization: Bearer your-jwt-token" ``` ```javascript Node.js theme={null} const response = await fetch('https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/exclusions', { headers: { 'Authorization': 'Bearer your-jwt-token' } }); const exclusions = await response.json(); console.log(exclusions); ``` ```python Python theme={null} import requests response = requests.get( 'https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/exclusions', headers={'Authorization': 'Bearer your-jwt-token'} ) exclusions = response.json() print(exclusions) ``` ```json Response theme={null} { "hasMore": false, "records": [ { "sid": "exc_abc123def456ghi789jkl012", "accountSid": "acc_abc123def456ghi789jkl012", "name": "Health Check Exclusion", "description": "Excludes health check endpoints from monitoring", "pathPattern": "/health*", "method": "GET", "statusCode": null, "isActive": true, "createdAt": "2023-12-01T10:30:00.000Z" }, { "sid": "exc_xyz789uvw012rst345abc", "accountSid": "acc_abc123def456ghi789jkl012", "name": "Static Assets", "description": "Excludes static asset requests", "pathPattern": "/static/*", "method": "*", "statusCode": null, "isActive": true, "createdAt": "2023-12-01T11:15:00.000Z" } ] } ``` *** ## Get Exclusion Retrieve details of a specific exclusion rule. ### Path Parameters Account identifier Exclusion rule identifier ### Headers Bearer token for authentication ### Response Returns a single exclusion object with the same structure as described in the List Exclusions response. ```bash cURL theme={null} curl -X GET "https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/exclusions/exc_abc123def456ghi789jkl012" \ -H "Authorization: Bearer your-jwt-token" ``` ```javascript Node.js theme={null} const response = await fetch('https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/exclusions/exc_abc123def456ghi789jkl012', { headers: { 'Authorization': 'Bearer your-jwt-token' } }); const exclusion = await response.json(); console.log(exclusion); ``` ```json Response theme={null} { "sid": "exc_abc123def456ghi789jkl012", "accountSid": "acc_abc123def456ghi789jkl012", "name": "Health Check Exclusion", "description": "Excludes health check endpoints from monitoring", "pathPattern": "/health*", "method": "GET", "statusCode": null, "isActive": true, "createdAt": "2023-12-01T10:30:00.000Z" } ``` *** ## Create Exclusion Create a new exclusion rule to filter out unwanted requests from monitoring. ### Path Parameters Account identifier ### Headers Bearer token for authentication ### Request Body Name of the exclusion rule Description of what this rule excludes URL path pattern to match. Supports wildcards (\*) and exact matches HTTP method to match (GET, POST, PUT, DELETE, etc.) or \* for all methods HTTP status code to match (optional, null means all status codes) Whether this exclusion rule should be active (default: true) ### Response Returns the created exclusion object. ```bash cURL theme={null} curl -X POST "https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/exclusions" \ -H "Authorization: Bearer your-jwt-token" \ -H "Content-Type: application/json" \ -d '{ "name": "Metrics Exclusion", "description": "Excludes internal metrics endpoints", "pathPattern": "/metrics/*", "method": "*", "isActive": true }' ``` ```javascript Node.js theme={null} const response = await fetch('https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/exclusions', { method: 'POST', headers: { 'Authorization': 'Bearer your-jwt-token', 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'Metrics Exclusion', description: 'Excludes internal metrics endpoints', pathPattern: '/metrics/*', method: '*', isActive: true }) }); const exclusion = await response.json(); console.log(exclusion); ``` ```python Python theme={null} import requests response = requests.post( 'https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/exclusions', headers={ 'Authorization': 'Bearer your-jwt-token', 'Content-Type': 'application/json' }, json={ 'name': 'Metrics Exclusion', 'description': 'Excludes internal metrics endpoints', 'pathPattern': '/metrics/*', 'method': '*', 'isActive': True } ) exclusion = response.json() print(exclusion) ``` ```json Response theme={null} { "sid": "exc_new789uvw012rst345def", "accountSid": "acc_abc123def456ghi789jkl012", "name": "Metrics Exclusion", "description": "Excludes internal metrics endpoints", "pathPattern": "/metrics/*", "method": "*", "statusCode": null, "isActive": true, "createdAt": "2023-12-01T15:45:00.000Z" } ``` *** ## Update Exclusion Update an existing exclusion rule. ### Path Parameters Account identifier Exclusion rule identifier ### Headers Bearer token for authentication ### Request Body Name of the exclusion rule Description of what this rule excludes URL path pattern to match HTTP method to match or \* for all methods HTTP status code to match (optional) Whether this exclusion rule should be active ### Response Returns the updated exclusion object. ```bash cURL theme={null} curl -X PUT "https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/exclusions/exc_abc123def456ghi789jkl012" \ -H "Authorization: Bearer your-jwt-token" \ -H "Content-Type: application/json" \ -d '{ "name": "Updated Health Check Exclusion", "description": "Excludes all health check and status endpoints", "pathPattern": "/health*", "method": "*", "statusCode": 200, "isActive": true }' ``` ```javascript Node.js theme={null} const response = await fetch('https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/exclusions/exc_abc123def456ghi789jkl012', { method: 'PUT', headers: { 'Authorization': 'Bearer your-jwt-token', 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'Updated Health Check Exclusion', description: 'Excludes all health check and status endpoints', pathPattern: '/health*', method: '*', statusCode: 200, isActive: true }) }); const exclusion = await response.json(); console.log(exclusion); ``` ```json Response theme={null} { "sid": "exc_abc123def456ghi789jkl012", "accountSid": "acc_abc123def456ghi789jkl012", "name": "Updated Health Check Exclusion", "description": "Excludes all health check and status endpoints", "pathPattern": "/health*", "method": "*", "statusCode": 200, "isActive": true, "createdAt": "2023-12-01T10:30:00.000Z" } ``` *** ## Delete Exclusion Delete an exclusion rule. Deleting an exclusion rule will cause previously excluded requests to be monitored again if they match other patterns. ### Path Parameters Account identifier Exclusion rule identifier ### Headers Bearer token for authentication ### Response ID of the deleted exclusion rule Flag indicating the exclusion rule was successfully deleted ```bash cURL theme={null} curl -X DELETE "https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/exclusions/exc_abc123def456ghi789jkl012" \ -H "Authorization: Bearer your-jwt-token" ``` ```javascript Node.js theme={null} const response = await fetch('https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/exclusions/exc_abc123def456ghi789jkl012', { method: 'DELETE', headers: { 'Authorization': 'Bearer your-jwt-token' } }); const result = await response.json(); console.log(result); ``` ```json Response theme={null} { "sid": "exc_abc123def456ghi789jkl012", "deleted": true } ``` *** ## Path Pattern Examples Exclusion rules support flexible path matching patterns: ```text Exact Match theme={null} /health // Matches only: /health ``` ```text Wildcard Suffix theme={null} /health* // Matches: /health, /health-check, /healthz ``` ```text Wildcard Prefix theme={null} */admin // Matches: /api/admin, /v1/admin, /internal/admin ``` ```text Wildcard Middle theme={null} /api/*/status // Matches: /api/users/status, /api/orders/status ``` ```text Multiple Wildcards theme={null} /api/*/v*/health* // Matches: /api/users/v1/health, /api/orders/v2/healthcheck ``` ## Common Exclusion Patterns ### Health Checks ```json theme={null} { "name": "Health Checks", "pathPattern": "/health*", "method": "GET" } ``` ### Static Assets ```json theme={null} { "name": "Static Assets", "pathPattern": "/static/*", "method": "*" } ``` ### Internal APIs ```json theme={null} { "name": "Internal APIs", "pathPattern": "/internal/*", "method": "*" } ``` ### Successful Options Requests ```json theme={null} { "name": "CORS Preflight", "pathPattern": "*", "method": "OPTIONS", "statusCode": 200 } ``` ### Admin Endpoints ```json theme={null} { "name": "Admin Panel", "pathPattern": "/admin/*", "method": "*" } ``` # Introduction Source: https://docs.apitraffic.io/api-reference/introduction REST API documentation for ApiTraffic platform ## Welcome to ApiTraffic API The ApiTraffic API provides programmatic access to your API monitoring data, configuration, and analytics. Our REST API is designed to be simple, predictable, and easy to integrate with your existing workflows. ## Base URL ``` https://api.apitraffic.io/v1 ``` ## Authentication All API requests require authentication using your API token. Include your token in the `Authorization` header: ```bash theme={null} curl -H "Authorization: Bearer your-api-token" \ https://api.apitraffic.io/v1/buckets ``` ## Rate Limiting API requests are rate limited to ensure fair usage: * **Standard Plan**: 1,000 requests per hour * **Pro Plan**: 10,000 requests per hour * **Enterprise Plan**: Custom limits Rate limit headers are included in all responses: ``` X-RateLimit-Limit: 1000 X-RateLimit-Remaining: 999 X-RateLimit-Reset: 1640995200 ``` ## Response Format All API responses are returned in JSON format: ```json theme={null} { "success": true, "data": { // Response data }, "meta": { "page": 1, "limit": 50, "total": 100 } } ``` ## Error Handling Errors are returned with appropriate HTTP status codes and descriptive messages: ```json theme={null} { "success": false, "error": { "code": "INVALID_TOKEN", "message": "The provided API token is invalid", "details": {} } } ``` ### Common Error Codes | Code | Description | | --------------------- | -------------------------------- | | `INVALID_TOKEN` | API token is missing or invalid | | `RATE_LIMIT_EXCEEDED` | Too many requests | | `RESOURCE_NOT_FOUND` | Requested resource doesn't exist | | `VALIDATION_ERROR` | Request validation failed | | `INTERNAL_ERROR` | Server error occurred | ## Pagination List endpoints support pagination using `page` and `limit` parameters: ```bash theme={null} curl "https://api.apitraffic.io/v1/requests?page=2&limit=25" \ -H "Authorization: Bearer your-api-token" ``` ## Filtering and Sorting Many endpoints support filtering and sorting: ```bash theme={null} # Filter by date range curl "https://api.apitraffic.io/v1/requests?start_date=2023-01-01&end_date=2023-01-31" \ -H "Authorization: Bearer your-api-token" # Sort by timestamp curl "https://api.apitraffic.io/v1/requests?sort=timestamp&order=desc" \ -H "Authorization: Bearer your-api-token" ``` ## SDKs and Libraries Official SDKs are available for popular languages: * **Node.js**: `@apitraffic/node-sdk` * **Python**: `apitraffic-python` * **PHP**: `apitraffic/php-sdk` * **Go**: `github.com/apitraffic/go-sdk` ## Getting Started 1. [Get your API token](https://app.apitraffic.io/settings/api) 2. Make your first API call 3. Explore the available endpoints 4. Integrate with your applications # MCP Tokens Source: https://docs.apitraffic.io/api-reference/mcp-tokens Manage MCP tokens for AI assistant access to your ApiTraffic data ## List MCP Tokens Retrieve all MCP tokens associated with an account. ### Path Parameters Account identifier (format: `acc_` followed by 27 alphanumeric characters) ### Headers Bearer token for authentication ### Response Indicates if there are more records to paginate through Unique MCP token identifier (format: `mcp_` prefix) Account identifier this token belongs to Environment this token is scoped to Array of bucket SIDs this token can access. Empty array means all buckets in the environment. Name of the MCP token Masked token value (full value only shown on creation) Whether this token has been revoked ISO 8601 timestamp of last token usage (nullable) ISO 8601 timestamp of token creation ```bash cURL theme={null} curl -X GET "https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/mcpTokens" \ -H "Authorization: Bearer your-jwt-token" ``` ```javascript Node.js theme={null} const response = await fetch('https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/mcpTokens', { headers: { 'Authorization': 'Bearer your-jwt-token' } }); const tokens = await response.json(); console.log(tokens); ``` ```json Response theme={null} { "hasMore": false, "records": [ { "sid": "mcp_abc123def456ghi789jkl012", "accountSid": "acc_abc123def456ghi789jkl012", "environmentSid": "prod01", "bucketSids": [], "name": "Claude Desktop - Production", "token": "mcp_2abc1*******ef789", "isRevoked": false, "lastUsedAt": "2025-03-15T14:30:00.000Z", "createdAt": "2025-03-15T10:30:00.000Z", "updatedAt": "2025-03-15T10:30:00.000Z", "revokedAt": null } ] } ``` *** ## Create MCP Token Create a new MCP token for AI assistant access. MCP tokens are read-only and scoped to a specific environment and set of buckets. ### Path Parameters Account identifier ### Headers Bearer token for authentication ### Request Body A descriptive name for the MCP token (e.g. "Claude Desktop - Production") The environment SID this token should be scoped to Array of bucket SIDs to restrict access to. Leave empty or omit to grant access to all buckets in the environment. ### Response Returns the created MCP token with the **full token value** (only shown once). The token value is only returned once during creation. Store it securely as it cannot be retrieved again. ```bash cURL theme={null} curl -X POST "https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/mcpTokens" \ -H "Authorization: Bearer your-jwt-token" \ -H "Content-Type: application/json" \ -d '{ "name": "Claude Desktop - Production", "environmentSid": "prod01", "bucketSids": [] }' ``` ```javascript Node.js theme={null} const response = await fetch('https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/mcpTokens', { method: 'POST', headers: { 'Authorization': 'Bearer your-jwt-token', 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'Claude Desktop - Production', environmentSid: 'prod01', bucketSids: [] }) }); const token = await response.json(); console.log(token); // Store token.token securely! ``` ```json Response theme={null} { "sid": "mcp_abc123def456ghi789jkl012", "accountSid": "acc_abc123def456ghi789jkl012", "environmentSid": "prod01", "bucketSids": [], "name": "Claude Desktop - Production", "token": "mcp_2abc1d3e4f5g6h7i8j9k0l1m2n3o4p5q6r7s8t9u0v1w2x3y4z", "isRevoked": false, "lastUsedAt": null, "createdAt": "2025-03-15T10:30:00.000Z", "updatedAt": "2025-03-15T10:30:00.000Z", "revokedAt": null } ``` *** ## Update MCP Token Update an existing MCP token's name or bucket scope. ### Path Parameters Account identifier MCP token identifier ### Headers Bearer token for authentication ### Request Body Updated name for the token Updated array of bucket SIDs (empty = all buckets in environment) ```bash cURL theme={null} curl -X PUT "https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/mcpTokens/mcp_abc123def456ghi789jkl012" \ -H "Authorization: Bearer your-jwt-token" \ -H "Content-Type: application/json" \ -d '{ "name": "Claude Desktop - Staging", "bucketSids": ["abc1234", "def5678"] }' ``` ```json Response theme={null} { "sid": "mcp_abc123def456ghi789jkl012", "accountSid": "acc_abc123def456ghi789jkl012", "environmentSid": "prod01", "bucketSids": ["abc1234", "def5678"], "name": "Claude Desktop - Staging", "token": "mcp_2abc1*******ef789", "isRevoked": false, "lastUsedAt": "2025-03-15T14:30:00.000Z", "createdAt": "2025-03-15T10:30:00.000Z", "updatedAt": "2025-03-15T15:00:00.000Z", "revokedAt": null } ``` *** ## Revoke MCP Token Revoke an MCP token, immediately terminating access for any AI assistants using it. This action is immediate. Any AI assistants using this token will lose access instantly. ### Path Parameters Account identifier MCP token identifier ### Headers Bearer token for authentication ```bash cURL theme={null} curl -X DELETE "https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/mcpTokens/mcp_abc123def456ghi789jkl012" \ -H "Authorization: Bearer your-jwt-token" ``` ```javascript Node.js theme={null} const response = await fetch('https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/mcpTokens/mcp_abc123def456ghi789jkl012', { method: 'DELETE', headers: { 'Authorization': 'Bearer your-jwt-token' } }); const result = await response.json(); console.log(result); ``` ```json Response theme={null} { "sid": "mcp_abc123def456ghi789jkl012", "deleted": true } ``` # Metrics Source: https://docs.apitraffic.io/api-reference/metrics Retrieve analytics and performance metrics for your API traffic ## Get Summary Metrics Retrieve summary metrics for an account, with optional filtering capabilities. ### Path Parameters Account identifier (format: `acc_` followed by 27 alphanumeric characters) ### Query Parameters Filter metrics by specific bucket Start date for metrics (ISO 8601 format) End date for metrics (ISO 8601 format) Filter by environment identifier ### Headers Bearer token for authentication ### Response Total number of requests in the time period Total number of error responses (4xx/5xx status codes) Average response time in milliseconds Total bytes transferred (request + response) Breakdown of requests by HTTP method Breakdown of requests by HTTP status code ranges Most frequently accessed endpoints ```bash cURL theme={null} curl -X GET "https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/metrics/summary?startDate=2023-12-01T00:00:00Z&endDate=2023-12-02T00:00:00Z" \ -H "Authorization: Bearer your-jwt-token" ``` ```javascript Node.js theme={null} const response = await fetch('https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/metrics/summary?startDate=2023-12-01T00:00:00Z&endDate=2023-12-02T00:00:00Z', { headers: { 'Authorization': 'Bearer your-jwt-token' } }); const metrics = await response.json(); console.log(metrics); ``` ```python Python theme={null} import requests response = requests.get( 'https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/metrics/summary', params={ 'startDate': '2023-12-01T00:00:00Z', 'endDate': '2023-12-02T00:00:00Z' }, headers={'Authorization': 'Bearer your-jwt-token'} ) metrics = response.json() print(metrics) ``` ```json Response theme={null} { "totalRequests": 15420, "totalErrors": 234, "averageResponseTime": 145.6, "totalDataTransferred": 2048576, "requestsByMethod": { "GET": 12340, "POST": 2100, "PUT": 680, "DELETE": 300 }, "requestsByStatus": { "2xx": 14186, "3xx": 1000, "4xx": 200, "5xx": 34 }, "topEndpoints": [ { "path": "/api/users", "count": 3420, "averageResponseTime": 120.5 }, { "path": "/api/orders", "count": 2100, "averageResponseTime": 180.2 } ] } ``` *** ## Get Throughput Metrics Retrieve request throughput metrics over time. ### Path Parameters Account identifier ### Query Parameters Filter metrics by specific bucket Start date for metrics (ISO 8601 format) End date for metrics (ISO 8601 format) Time interval for grouping: `hour`, `day`, `week`, `month` ### Headers Bearer token for authentication ### Response Time interval used for grouping ISO 8601 timestamp for the data point Number of requests in this time interval Number of errors in this time interval Average response time for this interval ```bash cURL theme={null} curl -X GET "https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/metrics/throughput?interval=hour&startDate=2023-12-01T00:00:00Z&endDate=2023-12-02T00:00:00Z" \ -H "Authorization: Bearer your-jwt-token" ``` ```javascript Node.js theme={null} const response = await fetch('https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/metrics/throughput?interval=hour&startDate=2023-12-01T00:00:00Z&endDate=2023-12-02T00:00:00Z', { headers: { 'Authorization': 'Bearer your-jwt-token' } }); const throughput = await response.json(); console.log(throughput); ``` ```json Response theme={null} { "interval": "hour", "data": [ { "timestamp": "2023-12-01T00:00:00Z", "requestCount": 450, "errorCount": 12, "averageResponseTime": 142.3 }, { "timestamp": "2023-12-01T01:00:00Z", "requestCount": 523, "errorCount": 8, "averageResponseTime": 138.7 } ] } ``` *** ## Get Performance Metrics Retrieve detailed performance metrics including response times, error rates, and endpoint analytics. ### Path Parameters Account identifier ### Query Parameters Filter metrics by specific bucket Start date for metrics (ISO 8601 format) End date for metrics (ISO 8601 format) Group metrics by: `endpoint`, `method`, `status`, `environment` ### Headers Bearer token for authentication ### Response The grouping method used The group identifier (endpoint, method, etc.) Total requests for this group Error rate as a percentage (0-100) Average response time in milliseconds 50th percentile response time 95th percentile response time 99th percentile response time ```bash cURL theme={null} curl -X GET "https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/metrics/performance?groupBy=endpoint&startDate=2023-12-01T00:00:00Z&endDate=2023-12-02T00:00:00Z" \ -H "Authorization: Bearer your-jwt-token" ``` ```javascript Node.js theme={null} const response = await fetch('https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/metrics/performance?groupBy=endpoint&startDate=2023-12-01T00:00:00Z&endDate=2023-12-02T00:00:00Z', { headers: { 'Authorization': 'Bearer your-jwt-token' } }); const performance = await response.json(); console.log(performance); ``` ```json Response theme={null} { "groupBy": "endpoint", "metrics": [ { "group": "/api/users", "requestCount": 3420, "errorRate": 1.2, "averageResponseTime": 120.5, "p50ResponseTime": 95.0, "p95ResponseTime": 280.0, "p99ResponseTime": 450.0 }, { "group": "/api/orders", "requestCount": 2100, "errorRate": 2.8, "averageResponseTime": 180.2, "p50ResponseTime": 145.0, "p95ResponseTime": 420.0, "p99ResponseTime": 650.0 } ] } ``` *** ## Get Error Metrics Retrieve detailed error analysis and patterns. ### Path Parameters Account identifier ### Query Parameters Filter metrics by specific bucket Start date for metrics (ISO 8601 format) End date for metrics (ISO 8601 format) Filter by specific HTTP status code ### Headers Bearer token for authentication ### Response Total number of errors in the time period Overall error rate as a percentage Breakdown of errors by HTTP status code API endpoint path Number of errors for this endpoint Error rate percentage for this endpoint Most frequent error status codes ```bash cURL theme={null} curl -X GET "https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/metrics/errors?startDate=2023-12-01T00:00:00Z&endDate=2023-12-02T00:00:00Z" \ -H "Authorization: Bearer your-jwt-token" ``` ```javascript Node.js theme={null} const response = await fetch('https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/metrics/errors?startDate=2023-12-01T00:00:00Z&endDate=2023-12-02T00:00:00Z', { headers: { 'Authorization': 'Bearer your-jwt-token' } }); const errors = await response.json(); console.log(errors); ``` ```json Response theme={null} { "totalErrors": 234, "errorRate": 1.52, "errorsByStatus": { "400": 120, "401": 45, "404": 35, "500": 25, "503": 9 }, "errorsByEndpoint": [ { "endpoint": "/api/auth/login", "errorCount": 45, "errorRate": 3.2, "mostCommonErrors": [401, 400] }, { "endpoint": "/api/users/profile", "errorCount": 35, "errorRate": 2.1, "mostCommonErrors": [404, 403] } ] } ``` # Redactions Source: https://docs.apitraffic.io/api-reference/redactions Manage data redaction rules to protect sensitive information ## List Redactions Retrieve all redaction rules configured for an account. ### Path Parameters Account identifier (format: `acc_` followed by 27 alphanumeric characters) ### Headers Bearer token for authentication ### Response Indicates if there are more records to paginate through Unique redaction rule identifier Account identifier this redaction belongs to Name of the redaction rule Description of what this rule redacts JSON path to the field to be redacted Type of redaction: `mask`, `remove`, `hash`, `replace` Value to use when redactionType is `replace` (nullable) Whether this redaction rule is currently active ISO 8601 timestamp of rule creation ```bash cURL theme={null} curl -X GET "https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/redactions" \ -H "Authorization: Bearer your-jwt-token" ``` ```javascript Node.js theme={null} const response = await fetch('https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/redactions', { headers: { 'Authorization': 'Bearer your-jwt-token' } }); const redactions = await response.json(); console.log(redactions); ``` ```python Python theme={null} import requests response = requests.get( 'https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/redactions', headers={'Authorization': 'Bearer your-jwt-token'} ) redactions = response.json() print(redactions) ``` ```json Response theme={null} { "hasMore": false, "records": [ { "sid": "red_abc123def456ghi789jkl012", "accountSid": "acc_abc123def456ghi789jkl012", "name": "Password Redaction", "description": "Redacts password fields from request bodies", "fieldPath": "$.password", "redactionType": "mask", "replacementValue": null, "isActive": true, "createdAt": "2023-12-01T10:30:00.000Z" }, { "sid": "red_xyz789uvw012rst345abc", "accountSid": "acc_abc123def456ghi789jkl012", "name": "Credit Card Masking", "description": "Masks credit card numbers", "fieldPath": "$.payment.cardNumber", "redactionType": "mask", "replacementValue": null, "isActive": true, "createdAt": "2023-12-01T11:15:00.000Z" } ] } ``` *** ## Get Redaction Retrieve details of a specific redaction rule. ### Path Parameters Account identifier Redaction rule identifier ### Headers Bearer token for authentication ### Response Returns a single redaction object with the same structure as described in the List Redactions response. ```bash cURL theme={null} curl -X GET "https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/redactions/red_abc123def456ghi789jkl012" \ -H "Authorization: Bearer your-jwt-token" ``` ```javascript Node.js theme={null} const response = await fetch('https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/redactions/red_abc123def456ghi789jkl012', { headers: { 'Authorization': 'Bearer your-jwt-token' } }); const redaction = await response.json(); console.log(redaction); ``` ```json Response theme={null} { "sid": "red_abc123def456ghi789jkl012", "accountSid": "acc_abc123def456ghi789jkl012", "name": "Password Redaction", "description": "Redacts password fields from request bodies", "fieldPath": "$.password", "redactionType": "mask", "replacementValue": null, "isActive": true, "createdAt": "2023-12-01T10:30:00.000Z" } ``` *** ## Create Redaction Create a new redaction rule to protect sensitive data. ### Path Parameters Account identifier ### Headers Bearer token for authentication ### Request Body Name of the redaction rule Description of what this rule redacts JSON path to the field to be redacted (e.g., `$.password`, `$.user.email`) Type of redaction: `mask`, `remove`, `hash`, or `replace` Value to use when redactionType is `replace` Whether this redaction rule should be active (default: true) ### Response Returns the created redaction object. ```bash cURL theme={null} curl -X POST "https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/redactions" \ -H "Authorization: Bearer your-jwt-token" \ -H "Content-Type: application/json" \ -d '{ "name": "Email Redaction", "description": "Masks email addresses in user data", "fieldPath": "$.user.email", "redactionType": "mask", "isActive": true }' ``` ```javascript Node.js theme={null} const response = await fetch('https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/redactions', { method: 'POST', headers: { 'Authorization': 'Bearer your-jwt-token', 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'Email Redaction', description: 'Masks email addresses in user data', fieldPath: '$.user.email', redactionType: 'mask', isActive: true }) }); const redaction = await response.json(); console.log(redaction); ``` ```python Python theme={null} import requests response = requests.post( 'https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/redactions', headers={ 'Authorization': 'Bearer your-jwt-token', 'Content-Type': 'application/json' }, json={ 'name': 'Email Redaction', 'description': 'Masks email addresses in user data', 'fieldPath': '$.user.email', 'redactionType': 'mask', 'isActive': True } ) redaction = response.json() print(redaction) ``` ```json Response theme={null} { "sid": "red_new789uvw012rst345def", "accountSid": "acc_abc123def456ghi789jkl012", "name": "Email Redaction", "description": "Masks email addresses in user data", "fieldPath": "$.user.email", "redactionType": "mask", "replacementValue": null, "isActive": true, "createdAt": "2023-12-01T15:45:00.000Z" } ``` *** ## Update Redaction Update an existing redaction rule. ### Path Parameters Account identifier Redaction rule identifier ### Headers Bearer token for authentication ### Request Body Name of the redaction rule Description of what this rule redacts JSON path to the field to be redacted Type of redaction: `mask`, `remove`, `hash`, or `replace` Value to use when redactionType is `replace` Whether this redaction rule should be active ### Response Returns the updated redaction object. ```bash cURL theme={null} curl -X PUT "https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/redactions/red_abc123def456ghi789jkl012" \ -H "Authorization: Bearer your-jwt-token" \ -H "Content-Type: application/json" \ -d '{ "name": "Updated Password Redaction", "description": "Redacts all password fields from requests and responses", "fieldPath": "$.password", "redactionType": "remove", "isActive": true }' ``` ```javascript Node.js theme={null} const response = await fetch('https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/redactions/red_abc123def456ghi789jkl012', { method: 'PUT', headers: { 'Authorization': 'Bearer your-jwt-token', 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'Updated Password Redaction', description: 'Redacts all password fields from requests and responses', fieldPath: '$.password', redactionType: 'remove', isActive: true }) }); const redaction = await response.json(); console.log(redaction); ``` ```json Response theme={null} { "sid": "red_abc123def456ghi789jkl012", "accountSid": "acc_abc123def456ghi789jkl012", "name": "Updated Password Redaction", "description": "Redacts all password fields from requests and responses", "fieldPath": "$.password", "redactionType": "remove", "replacementValue": null, "isActive": true, "createdAt": "2023-12-01T10:30:00.000Z" } ``` *** ## Delete Redaction Delete a redaction rule. Deleting a redaction rule will not affect previously redacted data, but new requests will no longer have this redaction applied. ### Path Parameters Account identifier Redaction rule identifier ### Headers Bearer token for authentication ### Response ID of the deleted redaction rule Flag indicating the redaction rule was successfully deleted ```bash cURL theme={null} curl -X DELETE "https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/redactions/red_abc123def456ghi789jkl012" \ -H "Authorization: Bearer your-jwt-token" ``` ```javascript Node.js theme={null} const response = await fetch('https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/redactions/red_abc123def456ghi789jkl012', { method: 'DELETE', headers: { 'Authorization': 'Bearer your-jwt-token' } }); const result = await response.json(); console.log(result); ``` ```json Response theme={null} { "sid": "red_abc123def456ghi789jkl012", "deleted": true } ``` *** ## Redaction Types ### Mask Replaces characters with asterisks while preserving format: * `john@example.com` → `j***@*******.com` * `4111111111111111` → `4***********1111` ### Remove Completely removes the field from the data: * `{"password": "secret123"}` → `{}` ### Hash Replaces the value with a SHA-256 hash: * `"secret123"` → `"a665a45920422f9d417e4867efdc4fb8a04a1f3fff1fa07e998e86f7f7a27ae3"` ### Replace Replaces the value with a specified replacement: * `"secret123"` → `"[REDACTED]"` (when replacementValue is `"[REDACTED]"`) ## JSON Path Examples ```json Simple Field theme={null} { "password": "secret123" } // JSON Path: $.password ``` ```json Nested Object theme={null} { "user": { "email": "john@example.com" } } // JSON Path: $.user.email ``` ```json Array Element theme={null} { "users": [ {"email": "john@example.com"}, {"email": "jane@example.com"} ] } // JSON Path: $.users[*].email ``` ```json Multiple Levels theme={null} { "order": { "payment": { "cardNumber": "4111111111111111" } } } // JSON Path: $.order.payment.cardNumber ``` # Requests Source: https://docs.apitraffic.io/api-reference/requests Manage and analyze API requests captured by ApiTraffic ## List Requests Retrieve all requests captured in a specific bucket. ### Path Parameters Account identifier (format: `acc_` followed by 27 alphanumeric characters) Bucket identifier ### Headers Bearer token for authentication ### Response Indicates if there are more records to paginate through Request identifier (format: `req_` followed by 27 alphanumeric characters) Bucket identifier this request belongs to Environment identifier (6 character alphanumeric, nullable) Request context identifier (nullable) Request direction: `in` (inbound) or `out` (outbound) User-added notes for the request (nullable) ISO 8601 timestamp when request was created ISO 8601 timestamp when request was received Whether the request was blocked by firewall rules Request host (nullable) HTTP method (nullable) Request path (nullable) Request port (nullable) Full request URL (nullable) Query string parameters Request headers as key-value pairs Request body content Content type of the request (nullable) Size of request payload in bytes (nullable) HTTP status code returned (nullable) Response headers as key-value pairs (nullable) Size of response payload in bytes (nullable) Response body content Content type of the response (nullable) Total request duration in milliseconds (nullable) Request start time (nullable) Request end time (nullable) DNS lookup time (nullable) Socket assignment time (nullable) Upload completion time (nullable) Connection establishment time (nullable) Response start time (nullable) ```bash cURL theme={null} curl -X GET "https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/buckets/bkt_xyz789uvw012rst345abc/requests" \ -H "Authorization: Bearer your-jwt-token" ``` ```javascript Node.js theme={null} const response = await fetch('https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/buckets/bkt_xyz789uvw012rst345abc/requests', { headers: { 'Authorization': 'Bearer your-jwt-token' } }); const requests = await response.json(); console.log(requests); ``` ```python Python theme={null} import requests response = requests.get( 'https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/buckets/bkt_xyz789uvw012rst345abc/requests', headers={'Authorization': 'Bearer your-jwt-token'} ) requests_data = response.json() print(requests_data) ``` ```json Response theme={null} { "hasMore": false, "records": [ { "sid": "req_abc123def456ghi789jkl012mno", "bucketSid": "bkt_xyz789uvw012rst345abc", "environmentSid": "env123", "contextSid": null, "direction": "in", "note": null, "createdAt": "2023-12-01T10:30:00.000Z", "receivedAt": "2023-12-01T10:30:00.100Z", "firewall": { "blocked": false }, "request": { "host": "api.example.com", "method": "GET", "path": "/users/123", "port": 443, "url": "https://api.example.com/users/123", "queryString": {}, "headers": { "user-agent": "Mozilla/5.0", "accept": "application/json" }, "body": null, "contentType": null, "size": 0 }, "response": { "statusCode": 200, "headers": { "content-type": "application/json", "content-length": "156" }, "size": 156, "body": { "id": 123, "name": "John Doe", "email": "john@example.com" }, "contentType": "application/json" }, "timings": { "duration": 245, "start": 1701423000000, "end": 1701423000245, "lookup": 12, "socket": 25, "upload": 30, "connect": 45, "response": 200 } } ] } ``` *** ## Get Request Retrieve details of a specific request. ### Path Parameters Account identifier Bucket identifier Request identifier ### Headers Bearer token for authentication ### Response Returns a single request object with the same structure as described in the List Requests response. ```bash cURL theme={null} curl -X GET "https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/buckets/bkt_xyz789uvw012rst345abc/requests/req_abc123def456ghi789jkl012mno" \ -H "Authorization: Bearer your-jwt-token" ``` ```javascript Node.js theme={null} const response = await fetch('https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/buckets/bkt_xyz789uvw012rst345abc/requests/req_abc123def456ghi789jkl012mno', { headers: { 'Authorization': 'Bearer your-jwt-token' } }); const request = await response.json(); console.log(request); ``` ```json Response theme={null} { "sid": "req_abc123def456ghi789jkl012mno", "bucketSid": "bkt_xyz789uvw012rst345abc", "environmentSid": "env123", "contextSid": null, "direction": "in", "note": null, "createdAt": "2023-12-01T10:30:00.000Z", "receivedAt": "2023-12-01T10:30:00.100Z", "firewall": { "blocked": false }, "request": { "host": "api.example.com", "method": "GET", "path": "/users/123", "port": 443, "url": "https://api.example.com/users/123", "queryString": {}, "headers": { "user-agent": "Mozilla/5.0", "accept": "application/json" }, "body": null, "contentType": null, "size": 0 }, "response": { "statusCode": 200, "headers": { "content-type": "application/json", "content-length": "156" }, "size": 156, "body": { "id": 123, "name": "John Doe", "email": "john@example.com" }, "contentType": "application/json" }, "timings": { "duration": 245, "start": 1701423000000, "end": 1701423000245, "lookup": 12, "socket": 25, "upload": 30, "connect": 45, "response": 200 } } ``` *** ## Update Request Update details of a specific request (typically used to add notes or modify metadata). ### Path Parameters Account identifier Bucket identifier Request identifier ### Headers Bearer token for authentication ### Request Body Add or update notes for the request ### Response Returns the updated request object. ```bash cURL theme={null} curl -X PUT "https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/buckets/bkt_xyz789uvw012rst345abc/requests/req_abc123def456ghi789jkl012mno" \ -H "Authorization: Bearer your-jwt-token" \ -H "Content-Type: application/json" \ -d '{ "note": "This request was flagged for review" }' ``` ```javascript Node.js theme={null} const response = await fetch('https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/buckets/bkt_xyz789uvw012rst345abc/requests/req_abc123def456ghi789jkl012mno', { method: 'PUT', headers: { 'Authorization': 'Bearer your-jwt-token', 'Content-Type': 'application/json' }, body: JSON.stringify({ note: 'This request was flagged for review' }) }); const request = await response.json(); console.log(request); ``` ```json Response theme={null} { "sid": "req_abc123def456ghi789jkl012mno", "bucketSid": "bkt_xyz789uvw012rst345abc", "environmentSid": "env123", "contextSid": null, "direction": "in", "note": "This request was flagged for review", "createdAt": "2023-12-01T10:30:00.000Z", "receivedAt": "2023-12-01T10:30:00.100Z", "firewall": { "blocked": false }, "request": { "host": "api.example.com", "method": "GET", "path": "/users/123", "port": 443, "url": "https://api.example.com/users/123", "queryString": {}, "headers": { "user-agent": "Mozilla/5.0", "accept": "application/json" }, "body": null, "contentType": null, "size": 0 }, "response": { "statusCode": 200, "headers": { "content-type": "application/json", "content-length": "156" }, "size": 156, "body": { "id": 123, "name": "John Doe", "email": "john@example.com" }, "contentType": "application/json" }, "timings": { "duration": 245, "start": 1701423000000, "end": 1701423000245, "lookup": 12, "socket": 25, "upload": 30, "connect": 45, "response": 200 } } ``` *** ## Delete Request Delete a specific request from the bucket. This action is irreversible. The request data will be permanently deleted. ### Path Parameters Account identifier Bucket identifier Request identifier ### Headers Bearer token for authentication ### Response ID of the deleted request Flag indicating the request was successfully deleted ```bash cURL theme={null} curl -X DELETE "https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/buckets/bkt_xyz789uvw012rst345abc/requests/req_abc123def456ghi789jkl012mno" \ -H "Authorization: Bearer your-jwt-token" ``` ```javascript Node.js theme={null} const response = await fetch('https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/buckets/bkt_xyz789uvw012rst345abc/requests/req_abc123def456ghi789jkl012mno', { method: 'DELETE', headers: { 'Authorization': 'Bearer your-jwt-token' } }); const result = await response.json(); console.log(result); ``` ```json Response theme={null} { "sid": "req_abc123def456ghi789jkl012mno", "deleted": true } ``` # Workflows Source: https://docs.apitraffic.io/api-reference/workflows Create and manage automated workflows based on API traffic patterns ## Create Workflow Create a new automated workflow that triggers based on API traffic patterns and conditions. ### Path Parameters Account identifier (format: `acc_` followed by 27 alphanumeric characters) Environment identifier (6 character alphanumeric) Bucket identifier ### Headers Bearer token for authentication ### Request Body Name of the workflow Description of what this workflow does Trigger type: `request`, `error`, `threshold`, `schedule` Array of conditions that must be met to trigger the workflow Cron expression for scheduled workflows (required if type is `schedule`) Action type: `webhook`, `email`, `slack`, `activepieces` Configuration specific to the action type Execution order for this action (default: 0) Whether this workflow should be active (default: true) ### Response Unique workflow identifier Account identifier this workflow belongs to Environment identifier Bucket identifier this workflow is associated with Name of the workflow Description of the workflow Trigger configuration Array of workflow actions Whether the workflow is currently active ISO 8601 timestamp of workflow creation ```bash cURL theme={null} curl -X POST "https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/environments/env123/buckets/bkt_xyz789uvw012rst345abc/workflows" \ -H "Authorization: Bearer your-jwt-token" \ -H "Content-Type: application/json" \ -d '{ "name": "Error Alert Workflow", "description": "Send Slack notification when error rate exceeds 5%", "trigger": { "type": "threshold", "conditions": [ { "metric": "error_rate", "operator": "greater_than", "value": 5, "timeWindow": "5m" } ] }, "actions": [ { "type": "slack", "config": { "webhook_url": "https://hooks.slack.com/services/...", "channel": "#alerts", "message": "🚨 Error rate exceeded 5% in {{bucket.name}}" }, "order": 1 } ], "isActive": true }' ``` ```javascript Node.js theme={null} const response = await fetch('https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/environments/env123/buckets/bkt_xyz789uvw012rst345abc/workflows', { method: 'POST', headers: { 'Authorization': 'Bearer your-jwt-token', 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'Error Alert Workflow', description: 'Send Slack notification when error rate exceeds 5%', trigger: { type: 'threshold', conditions: [ { metric: 'error_rate', operator: 'greater_than', value: 5, timeWindow: '5m' } ] }, actions: [ { type: 'slack', config: { webhook_url: 'https://hooks.slack.com/services/...', channel: '#alerts', message: '🚨 Error rate exceeded 5% in {{bucket.name}}' }, order: 1 } ], isActive: true }) }); const workflow = await response.json(); console.log(workflow); ``` ```python Python theme={null} import requests response = requests.post( 'https://api.apitraffic.io/v1/accounts/acc_abc123def456ghi789jkl012/environments/env123/buckets/bkt_xyz789uvw012rst345abc/workflows', headers={ 'Authorization': 'Bearer your-jwt-token', 'Content-Type': 'application/json' }, json={ 'name': 'Error Alert Workflow', 'description': 'Send Slack notification when error rate exceeds 5%', 'trigger': { 'type': 'threshold', 'conditions': [ { 'metric': 'error_rate', 'operator': 'greater_than', 'value': 5, 'timeWindow': '5m' } ] }, 'actions': [ { 'type': 'slack', 'config': { 'webhook_url': 'https://hooks.slack.com/services/...', 'channel': '#alerts', 'message': '🚨 Error rate exceeded 5% in {{bucket.name}}' }, 'order': 1 } ], 'isActive': True } ) workflow = response.json() print(workflow) ``` ```json Response theme={null} { "sid": "wfl_abc123def456ghi789jkl012", "accountSid": "acc_abc123def456ghi789jkl012", "environmentSid": "env123", "bucketSid": "bkt_xyz789uvw012rst345abc", "name": "Error Alert Workflow", "description": "Send Slack notification when error rate exceeds 5%", "trigger": { "type": "threshold", "conditions": [ { "metric": "error_rate", "operator": "greater_than", "value": 5, "timeWindow": "5m" } ] }, "actions": [ { "type": "slack", "config": { "webhook_url": "https://hooks.slack.com/services/...", "channel": "#alerts", "message": "🚨 Error rate exceeded 5% in {{bucket.name}}" }, "order": 1 } ], "isActive": true, "createdAt": "2023-12-01T15:45:00.000Z" } ``` *** ## Workflow Trigger Types ### Request Trigger Triggers when specific requests are made to your API. ```json theme={null} { "type": "request", "conditions": [ { "path": "/api/users", "method": "POST", "statusCode": 201 } ] } ``` ### Error Trigger Triggers when errors occur in your API. ```json theme={null} { "type": "error", "conditions": [ { "statusCode": 500, "path": "/api/*" } ] } ``` ### Threshold Trigger Triggers when metrics cross specified thresholds. ```json theme={null} { "type": "threshold", "conditions": [ { "metric": "response_time", "operator": "greater_than", "value": 1000, "timeWindow": "5m" } ] } ``` ### Schedule Trigger Triggers on a scheduled basis using cron expressions. ```json theme={null} { "type": "schedule", "schedule": "0 9 * * MON-FRI" } ``` *** ## Workflow Action Types ### Webhook Action Send HTTP requests to external services. ```json theme={null} { "type": "webhook", "config": { "url": "https://api.example.com/webhook", "method": "POST", "headers": { "Authorization": "Bearer token" }, "body": { "message": "Alert from ApiTraffic", "data": "{{request.body}}" } } } ``` ### Email Action Send email notifications. ```json theme={null} { "type": "email", "config": { "to": ["admin@example.com"], "subject": "API Alert: {{trigger.type}}", "body": "An alert was triggered in bucket {{bucket.name}}" } } ``` ### Slack Action Send messages to Slack channels. ```json theme={null} { "type": "slack", "config": { "webhook_url": "https://hooks.slack.com/services/...", "channel": "#alerts", "message": "🚨 {{trigger.message}}", "username": "ApiTraffic Bot" } } ``` ### ActivePieces Action Trigger ActivePieces workflows for complex automation. ```json theme={null} { "type": "activepieces", "config": { "flow_id": "flow_abc123", "webhook_url": "https://flow.apitraffic.io/webhook/...", "data": { "request": "{{request}}", "response": "{{response}}" } } } ``` *** ## Template Variables Workflows support template variables that are dynamically replaced with actual values: ### Request Variables * `{{request.method}}` - HTTP method * `{{request.path}}` - Request path * `{{request.headers}}` - Request headers * `{{request.body}}` - Request body * `{{request.query}}` - Query parameters ### Response Variables * `{{response.statusCode}}` - HTTP status code * `{{response.headers}}` - Response headers * `{{response.body}}` - Response body * `{{response.size}}` - Response size in bytes ### Timing Variables * `{{timings.duration}}` - Total request duration * `{{timings.responseTime}}` - Response time ### Context Variables * `{{bucket.name}}` - Bucket name * `{{bucket.sid}}` - Bucket ID * `{{account.name}}` - Account name * `{{environment.name}}` - Environment name ### Metric Variables (for threshold triggers) * `{{metric.value}}` - Current metric value * `{{metric.threshold}}` - Configured threshold * `{{metric.timeWindow}}` - Time window for the metric *** ## Common Workflow Examples ### High Error Rate Alert ```json theme={null} { "name": "High Error Rate Alert", "trigger": { "type": "threshold", "conditions": [ { "metric": "error_rate", "operator": "greater_than", "value": 10, "timeWindow": "5m" } ] }, "actions": [ { "type": "slack", "config": { "message": "🚨 Error rate is {{metric.value}}% in {{bucket.name}}" } } ] } ``` ### Slow Response Alert ```json theme={null} { "name": "Slow Response Alert", "trigger": { "type": "threshold", "conditions": [ { "metric": "avg_response_time", "operator": "greater_than", "value": 2000, "timeWindow": "10m" } ] }, "actions": [ { "type": "email", "config": { "subject": "Slow API Performance Alert", "body": "Average response time is {{metric.value}}ms" } } ] } ``` ### New User Registration ```json theme={null} { "name": "New User Registration", "trigger": { "type": "request", "conditions": [ { "path": "/api/users", "method": "POST", "statusCode": 201 } ] }, "actions": [ { "type": "webhook", "config": { "url": "https://crm.example.com/webhook", "body": { "event": "user_registered", "user_data": "{{request.body}}" } } } ] } ``` ### Daily Summary Report ```json theme={null} { "name": "Daily Summary Report", "trigger": { "type": "schedule", "schedule": "0 9 * * *" }, "actions": [ { "type": "email", "config": { "subject": "Daily API Summary for {{bucket.name}}", "body": "Your daily API traffic summary is ready." } } ] } ``` # Development Source: https://docs.apitraffic.io/development Set up your local development environment ## Local Development Setup Get your ApiTraffic development environment running locally. ### Prerequisites * Node.js (v18+ recommended) * npm or yarn * Git * Docker (optional, for containerized development) ### Installation 1. Clone the repository: ```bash theme={null} git clone https://github.com/apitraffic/platform.git cd platform ``` 2. Install dependencies: ```bash theme={null} npm install ``` ### Development Options #### Option 1: Full npm Development (Recommended) Run all services locally with npm for maximum development speed: ```bash theme={null} # Run all services concurrently npm run dev # Or run services individually npm run dev:api # API server on port 8081 npm run dev:processor # Background processor npm run dev:relay # Relay service on port 8082 npm run dev:ui # UI with Vite hot reloading on port 8080 ``` #### Option 2: Docker Development Run all services in Docker with volume mounts for live reloading: ```bash theme={null} # Using Docker Compose docker-compose -f docker-compose.dev.yml up -d # Or using direct Docker run docker run -d --name apitraffic-dev \ -p 8080:8080 -p 8081:8081 -p 8082:8082 \ -e SERVICES=all \ -e NODE_ENV=development \ --env-file .env.local \ -v $(pwd)/apps:/app/apps \ -v $(pwd)/libs:/app/libs \ apitraffic ``` ### Environment Configuration Create your local environment file: ```bash .env.local theme={null} NODE_ENV=local VITE_APP_ENV=local DATABASE_URL=postgresql://user:pass@localhost:5432/apitraffic API_TRAFFIC_TOKEN=your-dev-token API_TRAFFIC_BUCKET=your-dev-bucket ``` ### Available Scripts * `npm run dev` - Start all services in development mode * `npm run local` - Start all services with local configuration * `npm run build` - Build all applications * `npm run test` - Run tests * `npm run lint` - Lint the codebase * `npm run format` - Format code using Prettier ### Project Structure ``` apitraffic-app/ ├── apps/ # Applications │ ├── api/ # Main API server │ ├── processor/ # Background processor │ ├── relay/ # Traffic relay service │ └── ui/ # Frontend application ├── libs/ # Libraries │ ├── shared/ # Shared libraries │ └── client-libraries/ # Client SDK libraries └── docs/ # Documentation ``` ### Making Changes 1. Create a new branch for your feature 2. Make your changes 3. Run tests: `npm test` 4. Run linting: `npm run lint` 5. Submit a pull request ### Debugging For VS Code debugging, use the provided launch configurations in `.vscode/launch.json`. ```bash theme={null} # Debug specific service npm run dev:api # Then attach debugger to port 9229 ``` # Event Markers Source: https://docs.apitraffic.io/events Correlate deployments, incidents, and infrastructure changes with your API traffic ## What Are Event Markers? Event markers let you annotate your ApiTraffic dashboard with significant moments — deployments, incidents, configuration changes, scaling events — so you can visually correlate them with changes in your API's throughput, error rates, and response times. When an event is created, it appears as a **vertical line on your Throughput and Response Time charts**, making it immediately obvious whether a deploy caused a latency spike or an incident coincided with a drop in traffic. Event markers on dashboard charts ## Why Use Event Markers? Without event markers, correlating API behavior changes with infrastructure events means switching between dashboards, CI/CD logs, and incident timelines. Event markers bring all of that context into one view: * **Post-deploy verification** — Did error rates increase after the last release? * **Incident correlation** — When did the degradation start relative to the config change? * **Performance tracking** — Did the scaling event actually improve response times? * **Team visibility** — Everyone on the team can see what changed and when, without digging through deploy logs. ## Event Types | Type | When to use | | --------------- | --------------------------------------------------------------- | | `deployment` | Code releases, rollbacks, container image updates | | `incident` | Outages, degradations, alerts firing | | `config_change` | Feature flag toggles, environment variable updates, DNS changes | | `scale` | Autoscaling events, manual instance scaling, database upgrades | | `custom` | Anything else worth tracking | ## Creating Events There are three ways to create events, depending on your workflow. ### From the Dashboard Navigate to **Account → Events** in the left sidebar and click **Create Event**. This is useful for manually logging incidents or one-off events. You can set: * **Type** and **Name** (required) * **Description** and **Source** (optional context) * **Buckets** and **Environments** (scope the event or apply to all) * **Started At** and **Ended At** (defaults to now if left blank) ### From Your CI/CD Pipeline The most powerful use of events is **automated creation from your deployment pipeline**. By adding a single API call to the end of your deploy job, every release is automatically tracked on your charts. You'll need: 1. Your **Account SID** (found in Account Settings) 2. An **API Token** (create one under Account → API Tokens) Store both as secrets/environment variables in your CI/CD platform. ```yaml GitHub Actions theme={null} name: Deploy on: push: branches: [main] jobs: deploy: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 # ... your existing deploy steps ... - name: Create ApiTraffic Deploy Event if: success() run: | curl -s -X POST \ "https://api.apitraffic.io/v1/accounts/${{ secrets.APITRAFFIC_ACCOUNT_SID }}/events" \ -H "Authorization: Bearer ${{ secrets.APITRAFFIC_API_TOKEN }}" \ -H "Content-Type: application/json" \ -d '{ "type": "deployment", "name": "${{ github.ref_name }} @ ${{ github.sha }}", "description": "Deployed by ${{ github.actor }}", "source": "github_actions", "metadata": { "commitSha": "${{ github.sha }}", "branch": "${{ github.ref_name }}", "actor": "${{ github.actor }}", "runId": "${{ github.run_id }}", "runUrl": "${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}" } }' ``` ```yaml GitLab CI theme={null} deploy: stage: deploy script: # ... your existing deploy steps ... - | curl -s -X POST \ "https://api.apitraffic.io/v1/accounts/${APITRAFFIC_ACCOUNT_SID}/events" \ -H "Authorization: Bearer ${APITRAFFIC_API_TOKEN}" \ -H "Content-Type: application/json" \ -d "{ \"type\": \"deployment\", \"name\": \"${CI_COMMIT_TAG:-$CI_COMMIT_SHORT_SHA} deploy\", \"description\": \"Pipeline ${CI_PIPELINE_ID} by ${GITLAB_USER_LOGIN}\", \"source\": \"gitlab_ci\", \"metadata\": { \"commitSha\": \"${CI_COMMIT_SHA}\", \"branch\": \"${CI_COMMIT_BRANCH}\", \"pipelineId\": \"${CI_PIPELINE_ID}\", \"pipelineUrl\": \"${CI_PIPELINE_URL}\" } }" ``` ```groovy Jenkins (Jenkinsfile) theme={null} pipeline { agent any stages { stage('Deploy') { steps { // ... your existing deploy steps ... } } } post { success { sh """ curl -s -X POST \ "https://api.apitraffic.io/v1/accounts/\${APITRAFFIC_ACCOUNT_SID}/events" \ -H "Authorization: Bearer \${APITRAFFIC_API_TOKEN}" \ -H "Content-Type: application/json" \ -d '{ "type": "deployment", "name": "${env.BUILD_TAG}", "description": "Build #${env.BUILD_NUMBER}", "source": "jenkins", "metadata": { "buildNumber": "${env.BUILD_NUMBER}", "jobName": "${env.JOB_NAME}", "buildUrl": "${env.BUILD_URL}" } }' """ } } } ``` ```yaml CircleCI theme={null} version: 2.1 jobs: deploy: docker: - image: cimg/base:stable steps: # ... your existing deploy steps ... - run: name: Create ApiTraffic Deploy Event command: | curl -s -X POST \ "https://api.apitraffic.io/v1/accounts/${APITRAFFIC_ACCOUNT_SID}/events" \ -H "Authorization: Bearer ${APITRAFFIC_API_TOKEN}" \ -H "Content-Type: application/json" \ -d "{ \"type\": \"deployment\", \"name\": \"${CIRCLE_TAG:-$CIRCLE_SHA1}\", \"description\": \"Job ${CIRCLE_JOB} on ${CIRCLE_BRANCH}\", \"source\": \"circleci\", \"metadata\": { \"commitSha\": \"${CIRCLE_SHA1}\", \"branch\": \"${CIRCLE_BRANCH}\", \"buildUrl\": \"${CIRCLE_BUILD_URL}\" } }" ``` ```bash Generic Script theme={null} #!/bin/bash # deploy-event.sh — call this at the end of any deploy script ACCOUNT_SID="${APITRAFFIC_ACCOUNT_SID}" API_TOKEN="${APITRAFFIC_API_TOKEN}" EVENT_NAME="${1:-manual deploy}" curl -s -X POST \ "https://api.apitraffic.io/v1/accounts/${ACCOUNT_SID}/events" \ -H "Authorization: Bearer ${API_TOKEN}" \ -H "Content-Type: application/json" \ -d "{ \"type\": \"deployment\", \"name\": \"${EVENT_NAME}\", \"source\": \"manual\", \"metadata\": { \"hostname\": \"$(hostname)\", \"user\": \"$(whoami)\" } }" ``` ### From an AI Assistant (MCP) If you have an [MCP token](/api-reference/mcp-tokens) configured, AI assistants connected to ApiTraffic can create events using the `create_event` tool. This is useful for logging events conversationally: > "Create a deployment event for v2.3.1 release on the production bucket" The MCP server also exposes `list_events` for querying existing events. ## Scoping Events to Buckets & Environments By default, events apply to **all buckets** and **all environments** (represented as `["*"]`). This means the event annotation will appear on every dashboard. If your event only affects a specific service or environment, you can scope it: ```json theme={null} { "type": "deployment", "name": "payments-service v1.4.2", "bucketSids": ["bkt_abc123def456ghi789jkl012"], "environmentSids": ["env_prod789uvw012rst345abc"] } ``` Scoped events only appear on the matching bucket/environment dashboard, keeping charts clean and relevant. When using the dashboard UI to create events, toggle off "Apply to all" under Buckets or Environments to select specific targets. ## The Metadata Field The `metadata` field accepts any JSON object. Use it to store context that helps you trace from a chart annotation back to the exact change: ```json theme={null} { "metadata": { "commitSha": "a1b2c3d4e5f6", "branch": "main", "imageTag": "v2.3.1", "prNumber": 427, "prUrl": "https://github.com/org/repo/pull/427", "rollback": false } } ``` This data is stored with the event and returned in list/get API responses, making it available for auditing and automation. ## Point-in-Time vs Duration Events **Point-in-time events** have only a `startedAt` timestamp (or leave it blank to default to "now"). These are ideal for deploys, config changes, and scaling events — things that happen at a specific moment. **Duration events** have both `startedAt` and `endedAt` timestamps. These are ideal for incidents: ```json theme={null} { "type": "incident", "name": "Database connection pool exhaustion", "startedAt": "2024-01-15T14:00:00Z", "endedAt": "2024-01-15T14:45:00Z" } ``` You can create an incident event when it starts (without `endedAt`), then update it with the resolution time later using the [Update Event](/api-reference/events#update-event) API endpoint. ## Managing Events Navigate to **Account → Events** in the dashboard to view, create, and delete events. The table shows: * **Type** — color-coded badge * **Name** — event title * **Source** — where the event came from * **Started At** — when it occurred * **Actions** — delete events you no longer need For programmatic management, see the full [Events API Reference](/api-reference/events). ## Best Practices ### Automate Everything The most valuable events are the ones you don't have to remember to create. Add event creation to every deploy pipeline, every scaling automation, and every incident bot. ### Use Descriptive Names Include version numbers, service names, or ticket IDs so events are meaningful at a glance on the chart: * `payments-service v2.3.1` * `feature-flag: dark-mode enabled` * `INCIDENT-1234: API gateway timeout` ### Store Rich Metadata Commit SHAs, PR links, Docker image tags, and pipeline URLs make it trivial to trace from a traffic anomaly to the exact change that caused it. ### Scope When Possible If a deploy only touches one service, scope the event to that bucket. This keeps other dashboards uncluttered and makes the correlation signal stronger. ### Close Your Incidents When an incident is resolved, update the event with `endedAt` and a resolution description. This creates a clear record of impact duration. ### Standardize Source Names Pick consistent source identifiers across your team and pipelines: | Source | Use for | | ---------------- | ------------------------------------ | | `github_actions` | GitHub Actions workflows | | `gitlab_ci` | GitLab CI/CD pipelines | | `jenkins` | Jenkins jobs | | `circleci` | CircleCI workflows | | `argocd` | Argo CD sync events | | `manual` | Events created from the dashboard UI | | `mcp` | Events created via AI assistant | ## What's Next? Full CRUD API documentation with request/response examples Connect AI assistants to create and query events # Embeddable Request Log Source: https://docs.apitraffic.io/integrations/embed Embed an ApiTraffic request log directly into your application — like Stripe Elements for API traffic. Give your customers or internal teams a real-time view of API traffic without leaving your app. The embed SDK renders a fully styled, CSS-isolated request log using Web Components (Shadow DOM) — no iFrames, no style conflicts. The embed feature requires an **ApiTraffic API token** on your server to generate signed embed tokens. The client-side SDK never sees your API token. ## How It Works ```mermaid theme={null} sequenceDiagram participant Browser as Client Browser participant Server as Your Server participant AT as ApiTraffic API Browser->>Server: GET /api/embed-token Server->>AT: POST /v1/accounts/{id}/embeds/token AT-->>Server: { token, expiresAt } Server-->>Browser: { token } Browser->>AT: GET /v1/embed/requests (Bearer token) AT-->>Browser: Request log data ``` 1. Your **backend** calls the ApiTraffic API with your API token to generate a signed embed JWT. 2. The JWT locks in the bucket, filters, and theme — the client SDK cannot tamper with these. 3. Your **frontend** passes the JWT to the `` Web Component. 4. The component fetches data directly from ApiTraffic's embed endpoints using the JWT. ## Generate an Embed Token (Server-Side) ```javascript Node.js theme={null} const axios = require('axios'); async function getEmbedToken(accountSid, apiToken) { const response = await axios.post( `https://api.apitraffic.io/v1/accounts/${accountSid}/embeds/token`, { bucketSid: 'your-bucket-sid', view: 'request-log', filters: { environmentSid: 'abc123', // optional criteria: 'method == "GET"', // optional — same filter syntax as the dashboard streamViewSid: 'sv_...' // optional — use a saved stream view }, ttl: 3600, // seconds (min 60, max 86400) theme: 'light' // 'light' | 'dark' | 'auto' }, { headers: { Authorization: `Bearer ${apiToken}` } } ); return response.data; // { token, expiresAt } } ``` ```python Python theme={null} import requests def get_embed_token(account_sid, api_token): response = requests.post( f"https://api.apitraffic.io/v1/accounts/{account_sid}/embeds/token", json={ "bucketSid": "your-bucket-sid", "view": "request-log", "filters": { "environmentSid": "abc123", "criteria": 'method == "GET"' }, "ttl": 3600, "theme": "light" }, headers={"Authorization": f"Bearer {api_token}"} ) return response.json() # { "token": "...", "expiresAt": "..." } ``` ```bash cURL theme={null} curl -X POST "https://api.apitraffic.io/v1/accounts/acc_.../embeds/token" \ -H "Authorization: Bearer YOUR_API_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "bucketSid": "your-bucket-sid", "filters": { "criteria": "method == \"GET\"" }, "ttl": 3600, "theme": "light" }' ``` ### Token Parameters | Parameter | Type | Required | Default | Description | | ----------- | -------- | -------- | --------------- | --------------------------------------------------- | | `bucketSid` | `string` | Yes | — | The bucket to scope the embed to. | | `view` | `string` | No | `'request-log'` | The embed view type. | | `filters` | `object` | No | `{}` | Filters locked into the token (see below). | | `ttl` | `number` | No | `3600` | Token lifetime in seconds (60–86400). | | `theme` | `string` | No | `'light'` | Theme preference: `'light'`, `'dark'`, or `'auto'`. | ### Filter Options | Filter | Type | Description | | ---------------- | -------- | ------------------------------------------------ | | `environmentSid` | `string` | Filter to a specific environment. | | `criteria` | `string` | Search criteria string (same syntax as the API). | | `streamViewSid` | `string` | Use a saved stream view's filter criteria. | Filters are **server-side only**. They are cryptographically locked into the JWT — the client SDK cannot modify, add, or remove filters. This prevents data leakage. *** ## Vanilla JavaScript ### Installation ```bash npm theme={null} npm install @apitraffic/embed ``` ```bash yarn theme={null} yarn add @apitraffic/embed ``` ```bash CDN (no build step) theme={null} ``` ### Basic Usage ```html theme={null} ``` Or with ES module imports: ```javascript theme={null} import '@apitraffic/embed'; const el = document.querySelector('apitraffic-request-log'); el.token = await getTokenFromYourBackend(); ``` ### Attributes | Attribute | Type | Default | Description | | ------------- | -------- | -------------------------------- | ------------------------------------------ | | `token` | `string` | — | **Required.** The signed embed JWT. | | `theme` | `string` | `'light'` | `'light'`, `'dark'`, or `'auto'`. | | `api-url` | `string` | `'https://api.apitraffic.io/v1'` | Override the API base URL (self-hosted). | | `page-size` | `number` | `25` | Requests per page (1–100). | | `show-detail` | `string` | `'true'` | Set to `'false'` to disable row expansion. | ### Events ```javascript theme={null} const el = document.querySelector('apitraffic-request-log'); // Fires after the first successful data load el.addEventListener('apitraffic:ready', () => { console.log('Request log is ready'); }); // Fires on any API error el.addEventListener('apitraffic:error', (e) => { console.error('Error:', e.detail.message); }); // Fires ~30 seconds before the token expires el.addEventListener('apitraffic:token-expired', async () => { const { token } = await fetch('/api/embed-token').then(r => r.json()); el.token = token; // component re-fetches automatically }); // Fires when a request row is clicked el.addEventListener('apitraffic:request-click', (e) => { console.log('Clicked request:', e.detail.requestSid); }); ``` *** ## React ### Installation ```bash theme={null} npm install @apitraffic/embed-react @apitraffic/embed ``` ### Drop-In Component ```jsx theme={null} import { RequestLog } from '@apitraffic/embed-react'; function ApiLog({ token }) { return ( { const res = await fetch('/api/embed-token'); const { token } = await res.json(); return token; // returning the token auto-refreshes }} onReady={() => console.log('Loaded')} onError={(e) => console.error(e.detail)} onRequestClick={(e) => console.log(e.detail.requestSid)} /> ); } ``` ### Props | Prop | Type | Default | Description | | ---------------- | ---------- | --------- | ------------------------------------------ | | `token` | `string` | — | **Required.** The signed embed JWT. | | `theme` | `string` | `'light'` | `'light'`, `'dark'`, or `'auto'`. | | `apiUrl` | `string` | — | Override the API base URL. | | `pageSize` | `number` | `25` | Requests per page. | | `showDetail` | `boolean` | `true` | Enable/disable expandable row detail. | | `onTokenExpired` | `function` | — | Return a new token string to auto-refresh. | | `onReady` | `function` | — | Fires after the first successful load. | | `onError` | `function` | — | Fires on API errors. | | `onRequestClick` | `function` | — | Fires when a row is clicked. | ### Headless Hook Use `useApiTrafficEmbed` when you want full control over rendering: ```jsx theme={null} import { useApiTrafficEmbed } from '@apitraffic/embed-react'; function CustomLog({ token }) { const { requests, loading, loadingMore, error, hasMore, loadMore, refresh } = useApiTrafficEmbed({ token, pageSize: 50, onTokenExpired: async () => { const res = await fetch('/api/embed-token'); return (await res.json()).token; } }); if (loading) return

Loading...

; if (error) return

Error: {error}

; return (
{requests.map(req => (
{req.request?.method} {req.request?.path} — {req.response?.statusCode}
))} {hasMore && ( )}
); } ``` *** ## Theming The Web Component uses CSS custom properties for theming. Override them on the host element: ```css theme={null} apitraffic-request-log { /* Typography */ --at-font-family: 'Inter', sans-serif; --at-font-size: 13px; /* Colors */ --at-bg-color: #ffffff; --at-text-color: #1f2937; --at-text-muted: #6b7280; --at-accent-color: #3b82f6; --at-danger-color: #ef4444; /* Layout */ --at-border-color: #e5e7eb; --at-border-radius: 6px; --at-row-hover-bg: #f9fafb; --at-max-height: 600px; } ``` ### Available CSS Custom Properties | Property | Default | Description | | -------------------- | ----------------- | ------------------------------ | | `--at-font-family` | System font stack | Font family | | `--at-font-size` | `13px` | Base font size | | `--at-bg-color` | `#ffffff` | Container background | | `--at-text-color` | `#1f2937` | Primary text color | | `--at-text-muted` | `#6b7280` | Secondary/muted text | | `--at-accent-color` | `#3b82f6` | Links, buttons, GET method | | `--at-danger-color` | `#ef4444` | Errors, DELETE method | | `--at-border-color` | `#e5e7eb` | Border color | | `--at-border-radius` | `6px` | Container border radius | | `--at-row-hover-bg` | `#f9fafb` | Row hover background | | `--at-max-height` | `none` | Max height (set for scrolling) | ### Dark Mode Set `theme="dark"` for a built-in dark theme, or `theme="auto"` to follow the user's OS preference via `prefers-color-scheme`. *** ## Token Refresh Flow Embed tokens are short-lived by design. The SDK fires a `token-expired` event approximately 30 seconds before expiry, giving your app time to fetch a fresh token seamlessly: ```mermaid theme={null} sequenceDiagram participant Component as Embed Component participant App as Your App participant Server as Your Server participant AT as ApiTraffic API Note over Component: Token expires in 30s Component->>App: apitraffic:token-expired event App->>Server: GET /api/embed-token Server->>AT: POST .../embeds/token AT-->>Server: { token, expiresAt } Server-->>App: { token } App->>Component: el.token = newToken Note over Component: Re-fetches data with new token ``` *** ## Security All filters (bucket, environment, criteria, stream view) are cryptographically signed into the JWT using HMAC-SHA256. The client SDK reads the token to display data but cannot modify the filters. Any tampering invalidates the signature. No. The embed data endpoints extract the `accountSid`, `bucketSid`, and all filters directly from the verified JWT payload. Query parameters from the client are ignored for filtering — only pagination cursors (`from`, `limit`) are accepted. Tokens are short-lived (default 1 hour, max 24 hours) and scoped to a specific bucket and filter set. An attacker can only see the same data the embed was designed to show, and only until the token expires. You can also rotate the signing secret by calling the token endpoint — a new secret is auto-generated if the existing one is cleared. No. Your API token is only used **server-side** to generate embed JWTs. The browser only ever sees the embed JWT, which cannot be used to access any other ApiTraffic API endpoints. *** ## API Reference ### Create Embed Token ``` POST /v1/accounts/{accountSid}/embeds/token ``` **Authentication:** Bearer token (API token) **Request Body:** ```json theme={null} { "bucketSid": "string (required)", "view": "request-log", "filters": { "environmentSid": "string", "criteria": "string", "streamViewSid": "string" }, "ttl": 3600, "theme": "light" } ``` **Response:** ```json theme={null} { "token": "eyJhbGciOiJIUzI1NiJ9...", "expiresAt": "2025-03-17T05:27:00.000Z" } ``` ### Get Embed Requests ``` GET /v1/embed/requests?from={cursor}&limit={25} ``` **Authentication:** Bearer token (embed JWT) ### Get Embed Request Detail ``` GET /v1/embed/requests/{requestSid} ``` **Authentication:** Bearer token (embed JWT) *** ## Troubleshooting Verify the `bucketSid` in your token request matches a bucket that has traffic. Check that any filters aren't too restrictive. The embed token has likely expired. Implement the `apitraffic:token-expired` event handler (or `onTokenExpired` prop in React) to auto-refresh. The component uses Shadow DOM, so your page styles should not affect it. If you see issues, ensure you're setting CSS custom properties on the `apitraffic-request-log` element itself, not inside its shadow root. Ensure the SDK script or import is loaded before the element appears in the DOM. With the CDN approach, place the `