<!-- Cogny documentation. Canonical page: https://cogny.com/docs/api-overview-authentication -->

# Cogny API Overview and Authentication

Complete guide to authenticating with the Cogny API and understanding its core capabilities for programmatic access to growth analytics.

**Author:** Cogny Team  
**Published:** 2025-02-03  
**Updated:** 2026-10-05  
**Canonical:** https://cogny.com/docs/api-overview-authentication

## Overview

The Cogny API provides programmatic access to all core platform features, enabling you to integrate growth analytics and AI-powered insights directly into your workflows, dashboards, and applications.

**Base URL:** `https://api.cogny.com/v1`

**API Design:** RESTful architecture with JSON request/response payloads

**Rate Limits:**
- Standard tier: 100 requests/minute
- Enterprise tier: 1000 requests/minute
- Batch operations: 10 requests/minute

## Authentication

### API Key Generation

1. Navigate to **Settings > API Keys** in your Cogny dashboard
2. Click **Generate New API Key**
3. Provide a descriptive name (e.g., "Production Integration")
4. Select appropriate scopes:
   - `reports:read` - Read report data
   - `reports:write` - Create and modify reports
   - `tickets:read` - Access growth tickets
   - `warehouses:read` - Query warehouse metadata
   - `warehouses:write` - Modify warehouse settings

5. Save the API key securely (displayed only once)

### Authentication Methods

#### Bearer Token (Recommended)

Include your API key in the `Authorization` header:

```bash
curl -X GET https://api.cogny.com/v1/warehouses \
  -H "Authorization: Bearer sk_live_abc123xyz789" \
  -H "Content-Type: application/json"
```

#### API Key Header (Legacy)

Alternative method using custom header:

```bash
curl -X GET https://api.cogny.com/v1/warehouses \
  -H "X-API-Key: sk_live_abc123xyz789" \
  -H "Content-Type: application/json"
```

### Environment-Specific Keys

Cogny provides different key prefixes for environments:

- **Production:** `sk_live_...`
- **Development:** `sk_test_...`

Development keys access sandbox data and don't count toward rate limits.

## API Response Structure

### Success Response

All successful responses follow this structure:

```json
{
  "success": true,
  "data": {
    // Response payload specific to endpoint
  },
  "meta": {
    "timestamp": "2025-02-03T10:30:00Z",
    "request_id": "req_abc123"
  }
}
```

### Error Response

Errors return appropriate HTTP status codes with detailed messages:

```json
{
  "success": false,
  "error": {
    "code": "INVALID_PARAMETER",
    "message": "The 'warehouse_id' parameter is required",
    "details": {
      "parameter": "warehouse_id",
      "expected": "string (UUID format)"
    }
  },
  "meta": {
    "timestamp": "2025-02-03T10:30:00Z",
    "request_id": "req_abc123"
  }
}
```

### HTTP Status Codes

- **200 OK** - Successful request
- **201 Created** - Resource successfully created
- **400 Bad Request** - Invalid parameters or malformed request
- **401 Unauthorized** - Missing or invalid API key
- **403 Forbidden** - Insufficient permissions for requested resource
- **404 Not Found** - Resource doesn't exist
- **429 Too Many Requests** - Rate limit exceeded
- **500 Internal Server Error** - Server-side error (retry with exponential backoff)

## Pagination

List endpoints support cursor-based pagination for efficient data retrieval:

### Request Parameters

```bash
curl -X GET "https://api.cogny.com/v1/tickets?limit=50&cursor=eyJpZCI6MTIzfQ" \
  -H "Authorization: Bearer sk_live_abc123xyz789"
```

**Parameters:**
- `limit` (integer, optional): Number of items per page (default: 25, max: 100)
- `cursor` (string, optional): Pagination cursor from previous response

### Response Format

```json
{
  "success": true,
  "data": [
    // Array of items
  ],
  "pagination": {
    "has_more": true,
    "next_cursor": "eyJpZCI6MTczfQ",
    "total_count": 247
  }
}
```

### Pagination Example (Python)

```python
import requests

API_KEY = "sk_live_abc123xyz789"
BASE_URL = "https://api.cogny.com/v1"

headers = {
    "Authorization": f"Bearer {API_KEY}",
    "Content-Type": "application/json"
}

all_tickets = []
cursor = None

while True:
    params = {"limit": 100}
    if cursor:
        params["cursor"] = cursor

    response = requests.get(
        f"{BASE_URL}/tickets",
        headers=headers,
        params=params
    )
    data = response.json()

    all_tickets.extend(data["data"])

    if not data["pagination"]["has_more"]:
        break

    cursor = data["pagination"]["next_cursor"]

print(f"Retrieved {len(all_tickets)} tickets")
```

## Filtering and Sorting

### Filter Syntax

Use query parameters for filtering:

```bash
# Filter by status
curl -X GET "https://api.cogny.com/v1/tickets?status=open" \
  -H "Authorization: Bearer sk_live_abc123xyz789"

# Multiple filters
curl -X GET "https://api.cogny.com/v1/tickets?status=open&priority=high&created_after=2025-01-01" \
  -H "Authorization: Bearer sk_live_abc123xyz789"

# Date range filtering
curl -X GET "https://api.cogny.com/v1/reports?created_after=2025-01-01&created_before=2025-02-01" \
  -H "Authorization: Bearer sk_live_abc123xyz789"
```

### Common Filter Parameters

- `status` - Filter by status (varies by resource)
- `created_after` - ISO 8601 timestamp
- `created_before` - ISO 8601 timestamp
- `updated_after` - ISO 8601 timestamp
- `updated_before` - ISO 8601 timestamp

### Sorting

Use the `sort` parameter with optional direction:

```bash
# Sort by creation date (descending)
curl -X GET "https://api.cogny.com/v1/reports?sort=-created_at" \
  -H "Authorization: Bearer sk_live_abc123xyz789"

# Sort by priority (ascending)
curl -X GET "https://api.cogny.com/v1/tickets?sort=priority" \
  -H "Authorization: Bearer sk_live_abc123xyz789"
```

**Sort syntax:**
- Prefix with `-` for descending order
- No prefix for ascending order
- Common fields: `created_at`, `updated_at`, `priority`, `status`

## Webhooks

Subscribe to real-time events via webhooks:

### Event Types

- `report.completed` - Report generation finished
- `report.failed` - Report generation failed
- `ticket.created` - New growth ticket generated
- `ticket.updated` - Ticket status changed
- `warehouse.connected` - Data warehouse successfully connected
- `warehouse.sync_completed` - Data synchronization finished

### Webhook Configuration

Configure webhooks via API:

```bash
curl -X POST https://api.cogny.com/v1/webhooks \
  -H "Authorization: Bearer sk_live_abc123xyz789" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "https://your-app.com/webhooks/cogny",
    "events": ["report.completed", "ticket.created"],
    "secret": "whsec_your_webhook_secret"
  }'
```

### Webhook Payload

```json
{
  "id": "evt_abc123",
  "type": "report.completed",
  "created_at": "2025-02-03T10:30:00Z",
  "data": {
    "report_id": "rpt_xyz789",
    "warehouse_id": "wh_123abc",
    "status": "completed",
    "url": "https://app.cogny.com/reports/rpt_xyz789"
  }
}
```

### Webhook Security

Verify webhook signatures using the provided secret:

```python
import hmac
import hashlib

def verify_webhook(payload, signature, secret):
    """Verify webhook signature"""
    expected_signature = hmac.new(
        secret.encode(),
        payload.encode(),
        hashlib.sha256
    ).hexdigest()

    return hmac.compare_digest(signature, expected_signature)

# In your webhook handler
signature = request.headers.get('X-Cogny-Signature')
is_valid = verify_webhook(request.body, signature, WEBHOOK_SECRET)
```

## SDKs and Client Libraries

### Official SDKs

- **Python:** `pip install cogny-python`
- **JavaScript/TypeScript:** `npm install @cogny/sdk`
- **Go:** `go get github.com/cogny/cogny-go`

### Python SDK Example

```python
from cogny import Cogny

# Initialize client
client = Cogny(api_key="sk_live_abc123xyz789")

# List warehouses
warehouses = client.warehouses.list()

# Generate report
report = client.reports.create(
    warehouse_id="wh_123abc",
    prompt="Analyze conversion funnel performance for Q1 2025",
    include_visualizations=True
)

# Wait for completion
report = client.reports.wait(report.id, timeout=300)
print(f"Report completed: {report.url}")
```

### TypeScript SDK Example

```typescript
import { Cogny } from '@cogny/sdk';

const client = new Cogny({
  apiKey: process.env.COGNY_API_KEY
});

// Generate report
const report = await client.reports.create({
  warehouseId: 'wh_123abc',
  prompt: 'Analyze conversion funnel performance for Q1 2025',
  includeVisualizations: true
});

// Poll for completion
const completedReport = await client.reports.wait(report.id, {
  timeout: 300000
});

console.log(`Report completed: ${completedReport.url}`);
```

## Best Practices

### Error Handling

Implement robust error handling with retry logic:

```python
import time
import requests

def make_request_with_retry(url, headers, max_retries=3):
    """Make API request with exponential backoff"""
    for attempt in range(max_retries):
        try:
            response = requests.get(url, headers=headers)

            # Success
            if response.status_code == 200:
                return response.json()

            # Rate limited - wait and retry
            if response.status_code == 429:
                retry_after = int(response.headers.get('Retry-After', 60))
                time.sleep(retry_after)
                continue

            # Server error - exponential backoff
            if response.status_code >= 500:
                wait_time = 2 ** attempt
                time.sleep(wait_time)
                continue

            # Client error - don't retry
            response.raise_for_status()

        except requests.exceptions.RequestException as e:
            if attempt == max_retries - 1:
                raise
            time.sleep(2 ** attempt)

    raise Exception("Max retries exceeded")
```

### Rate Limit Management

Monitor rate limit headers:

```python
response = requests.get(url, headers=headers)

# Check rate limit status
remaining = int(response.headers.get('X-RateLimit-Remaining', 0))
reset_time = int(response.headers.get('X-RateLimit-Reset', 0))

if remaining < 10:
    wait_time = reset_time - time.time()
    print(f"Approaching rate limit. Reset in {wait_time}s")
```

### Request ID Tracking

Include request IDs for debugging:

```python
import uuid

request_id = str(uuid.uuid4())
headers = {
    "Authorization": f"Bearer {API_KEY}",
    "X-Request-ID": request_id
}

response = requests.post(url, headers=headers, json=data)
print(f"Request ID: {request_id}")
```

## Next Steps

- [Report Builder API Reference](/docs/report-builder-api-reference) - Generate reports programmatically
- [Growth Tickets API Reference](/docs/growth-tickets-api-reference) - Access AI-generated growth insights
- [Connect Your Data Sources](/docs/connect-your-data-sources) - Your BigQuery warehouse, the GA4 and Search Console links, and Bring Your Own Data

## Support

- **API Status:** [status.cogny.com](https://status.cogny.com)
- **Documentation:** [docs.cogny.com](https://docs.cogny.com)
- **Support:** support@cogny.com
- **Community:** [community.cogny.com](https://community.cogny.com)

---

In this section:

- Growth Tickets API Reference: https://cogny.com/docs/growth-tickets-api-reference
- Report Builder API Reference: https://cogny.com/docs/report-builder-api-reference
- **Cogny API Overview and Authentication** (this page): https://cogny.com/docs/api-overview-authentication

Source page: https://cogny.com/docs/api-overview-authentication  
All documentation: https://cogny.com/docs  
Cogny for agents: https://cogny.com/llms.txt
