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

# API Guide

> Authentication, rate limits, best practices, and integration guides for the Nia API

## Authentication

All API requests require authentication using an API key. Include your API key in the `Authorization` header:

```bash theme={null}
Authorization: Bearer YOUR_API_KEY
```

Get your API key at [app.trynia.ai](https://app.trynia.ai).

For autonomous agents, use [Agent Onboarding](/agent-onboarding) to create accounts and keys via API (`/v2/auth/signup`, `/v2/auth/verify`, `/v2/auth/login`, `/v2/auth/login/verify`) and then install the skill non-interactively.

<Warning>
  Store your API key in an environment variable or secret manager. Rotate it immediately if compromised.
</Warning>

## Base URL

All API endpoints are available at:

```
https://apigcp.trynia.ai/v2
```

***

## Rate Limits

View your current usage and limits at [app.trynia.ai](https://app.trynia.ai). See the [Pricing page](/pricing) for plan details.

When you exceed rate limits, the API returns a `429` status code:

```json theme={null}
{
  "error": "Rate limit exceeded",
  "status": 429
}
```

Rate limit headers are included in responses:

| Header                  | Description                          |
| ----------------------- | ------------------------------------ |
| `X-RateLimit-Limit`     | Rate limit ceiling for the endpoint  |
| `X-RateLimit-Remaining` | Remaining requests in current window |
| `X-RateLimit-Reset`     | Time when the rate limit resets      |
| `X-Monthly-Limit`       | Monthly request limit                |

***

## Quick Start Examples

### Index a Repository

```bash theme={null}
curl -X POST https://apigcp.trynia.ai/v2/sources \
  -H "Authorization: Bearer $NIA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"type": "repository", "repository": "vercel/ai"}'
```

### Index Documentation

```bash theme={null}
curl -X POST https://apigcp.trynia.ai/v2/sources \
  -H "Authorization: Bearer $NIA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"type": "documentation", "url": "https://sdk.vercel.ai/docs"}'
```

### Search Across Sources

```bash theme={null}
curl -X POST https://apigcp.trynia.ai/v2/search \
  -H "Authorization: Bearer $NIA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "mode": "query",
    "messages": [{"role": "user", "content": "How do I stream responses?"}],
    "repositories": ["vercel/ai"],
    "data_sources": ["Vercel AI SDK"]
  }'
```

### Deploy a Document Agent

```bash theme={null}
curl -X POST https://apigcp.trynia.ai/v2/document/agent \
  -H "Authorization: Bearer $NIA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "source_id": "your-pdf-source-id",
    "query": "What are the key findings?"
  }'
```

### Package Search (No Indexing Required)

```bash theme={null}
curl -X POST https://apigcp.trynia.ai/v2/packages/grep \
  -H "Authorization: Bearer $NIA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "registry": "npm",
    "package_name": "ai",
    "pattern": "streamText"
  }'
```

### Sandbox search (clone + read-only agent)

Run an ephemeral sandbox that clones a **public** repo URL and answers with a read-only agent — no indexing step. Use a full URL (not `org/repo` shorthand). See [Sandbox search](/sandbox-search) for SSE, job polling, and response fields.

```bash theme={null}
curl -X POST https://apigcp.trynia.ai/v2/sandbox/search \
  -H "Authorization: Bearer $NIA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "repository": "https://github.com/vercel/ai",
    "ref": "main",
    "query": "How does streamText relate to the data stream protocol?"
  }'
```

***

## Best Practices

### Use the Unified Search Endpoint

The `/search` endpoint supports four modes via a discriminator. Use `mode: "query"` for multi-source search, `mode: "universal"` for cross-source discovery, `mode: "web"` for web search, and `mode: "deep"` for multi-step research:

```bash theme={null}
curl -X POST https://apigcp.trynia.ai/v2/search \
  -H "Authorization: Bearer $NIA_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "mode": "query",
    "messages": [{"role": "user", "content": "authentication middleware implementation"}],
    "search_mode": "unified"
  }'
```

### Sandbox search vs unified search

[Sandbox search](/sandbox-search) (`POST /sandbox/search`) bills as a **`query`** like `/search`, but it clones the repository into an isolated VM for a file-grounded agent run. Prefer `/search` when your content is already indexed or you need multi-source retrieval; use sandbox search for one-off deep questions against a public Git URL without creating a source.

### Leverage Package Search for Dependencies

Search through 3,000+ packages across PyPI, NPM, Crates.io, and Go modules without indexing:

```python theme={null}
import requests

headers = {"Authorization": f"Bearer {NIA_API_KEY}"}

# Semantic search for understanding patterns
response = requests.post(
    "https://apigcp.trynia.ai/v2/packages/search",
    headers=headers,
    json={
        "registry": "py_pi",
        "package_name": "fastapi",
        "semantic_queries": ["How does dependency injection work?"]
    }
)
```

### Handle Rate Limits with Exponential Backoff

```python theme={null}
import time
import requests

def fetch_with_retry(url, headers, json_data, max_retries=3):
    for attempt in range(max_retries):
        response = requests.post(url, headers=headers, json=json_data)
        
        if response.status_code == 429:
            wait_time = 2 ** attempt
            print(f"Rate limited. Waiting {wait_time}s...")
            time.sleep(wait_time)
            continue
        
        return response
    
    raise Exception("Max retries exceeded")
```

### Monitor Indexing Progress

Large sources take time to index. Poll the status endpoint:

```bash theme={null}
# Check source status
curl https://apigcp.trynia.ai/v2/sources/{source_id} \
  -H "Authorization: Bearer $NIA_API_KEY"
```

Response includes status:

```json theme={null}
{
  "id": "source-uuid",
  "type": "repository",
  "display_name": "vercel/ai",
  "status": "indexing",
  "identifier": "vercel/ai"
}
```

For a quick inventory of all sources:

```bash theme={null}
curl https://apigcp.trynia.ai/v2/sources-summary \
  -H "Authorization: Bearer $NIA_API_KEY"
```

***

## Error Handling

The Nia API uses standard HTTP status codes:

| Code | Description  | Action                                            |
| ---- | ------------ | ------------------------------------------------- |
| 200  | Success      | Process the response normally                     |
| 400  | Bad Request  | Check request parameters                          |
| 401  | Unauthorized | Verify your API key                               |
| 404  | Not Found    | Resource doesn't exist                            |
| 429  | Rate Limited | Implement backoff and retry                       |
| 500  | Server Error | Retry with backoff, contact support if persistent |

### Error Response Format

```json theme={null}
{
  "error": "Error message describing what went wrong",
  "status": 429
}
```

***

## SDK & Integration Options

### MCP Server (Recommended for AI Agents)

The easiest way to integrate Nia with AI coding agents:

```bash theme={null}
curl -fsSL https://app.trynia.ai/cli | sh
```

See the [Installation guide](/integrations/installation/overview) for detailed setup.

### Direct API Integration

For custom applications, use the REST API directly:

**JavaScript/TypeScript:**

```javascript theme={null}
const response = await fetch("https://apigcp.trynia.ai/v2/search", {
  method: "POST",
  headers: {
    "Authorization": `Bearer ${process.env.NIA_API_KEY}`,
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    mode: "query",
    messages: [{ role: "user", content: "How does error handling work?" }],
    repositories: ["fastapi/fastapi"]
  })
});

const results = await response.json();
```

**Python:**

```python theme={null}
import requests

headers = {
    "Authorization": f"Bearer {os.environ['NIA_API_KEY']}",
    "Content-Type": "application/json"
}

response = requests.post(
    "https://apigcp.trynia.ai/v2/search",
    headers=headers,
    json={
        "mode": "query",
        "messages": [{"role": "user", "content": "How does error handling work?"}],
        "repositories": ["fastapi/fastapi"]
    }
)

results = response.json()
```

***

## Key Endpoints

| Endpoint                    | Description                                                                                              |
| --------------------------- | -------------------------------------------------------------------------------------------------------- |
| `POST /sources`             | Create/index any source (repository, documentation, paper, dataset, local folder)                        |
| `GET /sources`              | List all indexed sources                                                                                 |
| `POST /search`              | Unified search with mode: `query`, `web`, `deep`, `universal`                                            |
| `POST /sandbox/search`      | Clone a public Git URL in an ephemeral sandbox and run read-only agent search ([guide](/sandbox-search)) |
| `GET /sandbox/jobs/{jobId}` | Get status and result for a sandbox search job                                                           |
| `POST /document/agent`      | Deploy an autonomous AI agent into a document (structured output, citations)                             |
| `POST /extract`             | Extract structured data from PDFs                                                                        |
| `POST /oracle/jobs`         | Start an Oracle research job                                                                             |
| `POST /github/tracer`       | Live GitHub code search agent                                                                            |
| `POST /packages/search`     | Semantic search in package source code                                                                   |
| `POST /packages/grep`       | Regex search in package source code                                                                      |
| `POST /contexts`            | Save cross-agent conversation context                                                                    |
| `GET /sources-summary`      | Quick inventory of all source types                                                                      |
| `GET /usage`                | API usage statistics and limits                                                                          |

<Info>
  Check out the [API Reference](/api-reference) for complete endpoint documentation with request/response schemas.
</Info>
