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

# Authentication

> API key management and authentication

## Overview

The 1tx API uses **API key authentication** for all requests. API keys are tied to your account and can be managed through the dashboard.

Some execution endpoints, such as `POST /transactions/buy` and `POST /transactions/sell`, also require a bearer token because they are wallet-user scoped.

## Getting an API Key

<Steps>
  <Step title="Create an Account">
    Sign up at [https://app.1tx.fi/signup](https://app.1tx.fi/signup)
  </Step>

  <Step title="Navigate to API Keys">
    Go to **Settings → API Keys** in your dashboard
  </Step>

  <Step title="Generate a New Key">
    Click **"Generate New API Key"** and give it a descriptive name

    Example names:

    * `production-app`
    * `staging-environment`
    * `development-local`
  </Step>

  <Step title="Copy Your Key">
    **Important:** Copy the key immediately - it will only be shown once!

    ```
    dx_sk_live_1234567890abcdefghijklmnopqrstuvwxyz
    ```
  </Step>

  <Step title="Store Securely">
    Store your API key in environment variables, never hardcode it:

    ```bash theme={null}
    # .env
    1TX_API_KEY=dx_sk_live_1234567890abcdefghijklmnopqrstuvwxyz
    ```
  </Step>
</Steps>

## Using API Keys

### In HTTP Requests

Include your API key in the `x-api-key` header:

```bash theme={null}
curl -H "x-api-key: dx_sk_live_1234567890abcdefghijklmnopqrstuvwxyz" \
  https://api.1tx.fi/api/v1/instruments
```

### Transaction Build Endpoints

For execution-oriented endpoints, send both headers:

```bash theme={null}
curl -X POST "https://api.1tx.fi/api/v1/transactions/buy" \
  -H "Authorization: Bearer <your_jwt>" \
  -H "x-api-key: dx_sk_live_1234567890abcdefghijklmnopqrstuvwxyz" \
  -H "Content-Type: application/json" \
  -d '{
    "userAddress": "0x...",
    "instrumentId": "0x...",
    "amountUsdc": "1000"
  }'
```

Use this pattern for:

* `POST /transactions/buy`
* `POST /transactions/sell`
* `GET /transactions/balances/:userAddress`

### With JavaScript/TypeScript

```typescript theme={null}
const API_KEY = process.env['1TX_API_KEY'];

async function fetchInstruments() {
  const response = await fetch('https://api.1tx.fi/api/v1/instruments', {
    headers: {
      'x-api-key': API_KEY,
      'Content-Type': 'application/json',
    },
  });

  if (!response.ok) {
    throw new Error(`API error: ${response.status}`);
  }

  return response.json();
}
```

### With Python

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

API_KEY = os.environ['1TX_API_KEY']

def fetch_instruments():
    response = requests.get(
        'https://api.1tx.fi/api/v1/instruments',
        headers={
            'x-api-key': API_KEY,
            'Content-Type': 'application/json'
        }
    )
    response.raise_for_status()
    return response.json()
```

### With SDK

```typescript theme={null}
import { 1txClient } from '@1tx/sdk';

const client = new 1txClient({
  apiKey: process.env.1TX_API_KEY,
});

// SDK handles authentication automatically
const instruments = await client.instruments.list();
```

## API Key Types

### Test Keys

**Prefix:** `dx_sk_test_`

* Use in development and testing
* Access to test environment only
* Unlimited requests
* No charges

```bash theme={null}
# Test key example
dx_sk_test_1234567890abcdefghijklmnopqrstuvwxyz
```

### Live Keys

**Prefix:** `dx_sk_live_`

* Use in production
* Access to mainnet data
* Subject to rate limits
* Charges apply

```bash theme={null}
# Live key example
dx_sk_live_1234567890abcdefghijklmnopqrstuvwxyz
```

## Managing API Keys

### View All Keys

```bash theme={null}
GET /api/v1/api-keys
```

```typescript theme={null}
const response = await fetch('https://api.1tx.fi/api/v1/api-keys', {
  headers: {
    'x-api-key': API_KEY,
  },
});

const { data } = await response.json();
// Returns list of all your keys with metadata
```

**Response:**

```json theme={null}
{
  "data": [
    {
      "id": "key_123abc",
      "name": "production-app",
      "prefix": "dx_sk_live_",
      "lastUsed": "2024-01-15T14:30:00Z",
      "createdAt": "2024-01-01T10:00:00Z",
      "expiresAt": null,
      "status": "active"
    }
  ]
}
```

### Update an API Key

```bash theme={null}
PATCH /api/v1/api-keys/:id
```

```typescript theme={null}
const response = await fetch('https://api.1tx.fi/api/v1/api-keys/key_123abc', {
  method: 'PATCH',
  headers: {
    'x-api-key': API_KEY,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    name: 'new-name',
    status: 'inactive'
  }),
});
```

### Delete an API Key

```bash theme={null}
DELETE /api/v1/api-keys/:id
```

```typescript theme={null}
const response = await fetch('https://api.1tx.fi/api/v1/api-keys/key_123abc', {
  method: 'DELETE',
  headers: {
    'x-api-key': API_KEY,
  },
});
```

### Create a New Key

```bash theme={null}
POST /api/v1/api-keys
```

```typescript theme={null}
const response = await fetch('https://api.1tx.fi/api/v1/api-keys', {
  method: 'POST',
  headers: {
    'x-api-key': API_KEY,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    name: 'staging-environment',
    expiresAt: '2024-12-31T23:59:59Z', // Optional
  }),
});

const { data } = await response.json();
console.log('New API key:', data.key);
```

**Response:**

```json theme={null}
{
  "data": {
    "id": "key_456def",
    "name": "staging-environment",
    "key": "dx_sk_live_1234567890abcdefghijklmnopqrstuvwxyz",
    "prefix": "dx_sk_live_",
    "createdAt": "2024-01-15T15:00:00Z",
    "expiresAt": "2024-12-31T23:59:59Z"
  }
}
```

<Warning>
  The full API key is only returned once during creation. Store it securely!
</Warning>

## Rate Limiting

Rate limits are enforced per API key:

```json theme={null}
// Response headers
{
  "X-RateLimit-Limit": "10000",
  "X-RateLimit-Remaining": "9850",
  "X-RateLimit-Reset": "1642261200"
}
```

## Error Responses

### 401 Unauthorized

**Missing API key:**

```json theme={null}
{
  "error": {
    "code": "UNAUTHORIZED",
    "message": "API key is required. Include it in the x-api-key header.",
    "details": {
      "timestamp": "2024-01-15T14:30:00Z"
    }
  }
}
```

**Invalid API key:**

```json theme={null}
{
  "error": {
    "code": "INVALID_API_KEY",
    "message": "The provided API key is invalid or has been revoked.",
    "details": {
      "timestamp": "2024-01-15T14:30:00Z"
    }
  }
}
```

### 403 Forbidden

**Insufficient permissions:**

```json theme={null}
{
  "error": {
    "code": "FORBIDDEN",
    "message": "Your API key does not have permission to access this resource.",
    "details": {
      "timestamp": "2024-01-15T14:30:00Z"
    }
  }
}
```

### 429 Too Many Requests

**Rate limit exceeded:**

```json theme={null}
{
  "error": {
    "code": "RATE_LIMIT_EXCEEDED",
    "message": "You have exceeded your API rate limit.",
    "details": {
      "limit": 10000,
      "resetAt": "2024-01-15T15:00:00Z"
    }
  }
}
```

## Next Steps

<CardGroup cols={2}>
  <Card title="API Reference" icon="code" href="/api-reference/introduction">
    Start making API calls
  </Card>

  <Card title="Instruments API" icon="fingerprint" href="/api-reference/endpoints/instruments">
    Query DeFi instruments
  </Card>

  <Card title="Integration Guide" icon="book" href="/integration/overview">
    Choose your integration model
  </Card>

  <Card title="How It Works" icon="gears" href="/how-it-works">
    Understand the transaction flow
  </Card>
</CardGroup>
