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

# API Keys Introduction

> Create and manage Lettr API keys to authenticate requests, with live and sandbox key types, permission levels, and IP restrictions

API keys authenticate your requests to the Lettr API. Each key is associated with a specific team and can be configured with different permission levels and IP restrictions for enhanced security.

## Creating API Keys

You can create API keys through the Lettr dashboard:

1. Navigate to **Settings** > **API Keys** in your dashboard
2. Click **Create API Key**
3. Enter a descriptive name for the key (e.g., "Production Server", "Staging Environment")
4. Select the appropriate permission level
5. Optionally, configure IP restrictions
6. Click **Create**

<Warning>
  The full API key is only displayed once upon creation. Copy and store it securely immediately. You will not be able to view the complete key again.
</Warning>

<Card title="Try it in the app" icon="wand-magic-sparkles" href="https://app.lettr.com/api-keys?guide=eyJ2IjoxLCJzdGVwcyI6W3siYW5jaG9yIjoiYXBpLWtleXMuY3JlYXRlIiwibWVzc2FnZSI6IkNyZWF0ZSBhIG5ldyBBUEkga2V5IGhlcmUgdG8gYXV0aGVudGljYXRlIHlvdXIgcmVxdWVzdHMgdG8gdGhlIExldHRyIEFQSS4ifSx7ImFuY2hvciI6ImFwaS1rZXlzLm5hbWUtaW5wdXQiLCJtZXNzYWdlIjoiR2l2ZSB0aGUga2V5IGEgZGVzY3JpcHRpdmUgbmFtZSBsaWtlIFByb2R1Y3Rpb24gb3IgU3RhZ2luZyBzbyB5b3UgY2FuIHRlbGwgeW91ciBrZXlzIGFwYXJ0IGxhdGVyLiJ9LHsiYW5jaG9yIjoiYXBpLWtleXMuc3VibWl0IiwibWVzc2FnZSI6IkNyZWF0ZSB0aGUga2V5LCB0aGVuIGNvcHkgaXQgbm93LiBGb3Igc2VjdXJpdHkgdGhlIGZ1bGwga2V5IGlzIHNob3duIG9ubHkgb25jZS4ifV0sImRvY3MiOiJodHRwczovL2RvY3MubGV0dHIuY29tL2xlYXJuL2FwaS1rZXlzL2ludHJvZHVjdGlvbiJ9">
  Follow an interactive walkthrough of this guide inside Lettr.
</Card>

## Key Types

Lettr supports two API key types:

* **Live** — for production use. Sends real emails to actual recipients and counts against your billing quota.
* **Sandbox** — for testing. Redirects all emails to your own inbox, uses a sandbox sending domain, and doesn't affect billing. See the [Sandbox API Keys](/learn/api-keys/sandbox) guide for details.

## Key Format

Lettr API keys follow this format:

```
lttr_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
```

Sandbox keys have a distinct prefix:

```
lttr_sandbox_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
```

* `lttr_` prefix identifies it as a live Lettr API key
* `lttr_sandbox_` prefix identifies it as a sandbox key
* Followed by a 64-character cryptographically secure random string

## Using API Keys

### Authorization Header (Recommended)

Include your API key in the `Authorization` header using the Bearer scheme:

```bash theme={null}
curl https://app.lettr.com/api/emails \
  -X POST \
  -H "Authorization: Bearer lttr_xxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{"from": "sender@example.com", "to": ["recipient@example.com"], "subject": "Hello", "html": "<p>Hello!</p>"}'
```

### In SDKs

When using official Lettr SDKs, pass your API key during client initialization:

<CodeGroup>
  ```javascript Node.js theme={null}
  import { Lettr } from 'lettr';

  const lettr = new Lettr(process.env.LETTR_API_KEY);
  ```

  ```php PHP theme={null}
  use Lettr\Client;

  $lettr = new Client(getenv('LETTR_API_KEY'));
  ```
</CodeGroup>

## Permission Levels

When creating an API key, you can choose between two permission levels:

* **Full Access** — grants access to all API endpoints, including sending emails, managing templates, domains, webhooks, and projects.
* **Sending Only** — restricted to sending operations only (emails, SMS, and WhatsApp). Requests to any other endpoint will be rejected with a `403 Forbidden` response.

Permission levels are fully enforced. Choose the level that matches your use case, and apply the [principle of least privilege](/learn/api-keys/permissions) by using **Sending Only** keys wherever full access isn't needed.

## IP Restrictions

For additional security, you can restrict API keys to specific IP addresses or ranges:

* **Single IP**: `203.0.113.50`
* **CIDR notation**: `198.51.100.0/24`
* **Multiple entries**: Combine IPs and ranges separated by commas

When IP restrictions are configured, requests from non-whitelisted IPs will receive a `403 Forbidden` response.

## Managing API Keys

### Viewing Your Keys

Access your API keys in the dashboard at **Settings** > **API Keys**. The list displays:

* Key name
* First 12 characters of the key (masked for security)
* Permission level
* IP restriction status
* Active status

### Updating a Key

You can modify the following properties of an existing API key:

* Name
* Permission level
* IP restrictions

<Note>
  The API key value itself cannot be changed. If you need a new key value, create a new key and delete the old one.
</Note>

### Revoking a Key

To revoke an API key:

1. Navigate to **Settings** > **API Keys**
2. Click the actions menu (three dots) next to the key
3. Select **Delete**
4. Type the key name to confirm deletion
5. Click **Delete** to confirm

<Warning>
  Revoking a key is immediate and permanent. Any applications using the key will immediately stop working. Ensure you have updated all applications using the key before revoking it.
</Warning>

## Best Practices

<AccordionGroup>
  <Accordion title="Never expose keys in client-side code">
    API keys should only be used server-side. Never include them in frontend JavaScript, mobile apps, or any code that runs on user devices. Exposed keys can be extracted and abused.
  </Accordion>

  <Accordion title="Use environment variables">
    Store API keys in environment variables rather than hardcoding them in your source code. This prevents accidental exposure through version control systems.

    ```bash theme={null}
    # .env file (never commit this)
    LETTR_API_KEY=lttr_xxxxxxxxxxxx
    ```
  </Accordion>

  <Accordion title="Apply the principle of least privilege">
    Create keys with only the permissions required for their specific purpose. Use **Sending Only** keys for applications that don't need full access.
  </Accordion>

  <Accordion title="Configure IP restrictions for production">
    Restrict production API keys to your server's IP addresses or IP ranges. This adds a layer of security even if a key is compromised.
  </Accordion>

  <Accordion title="Use descriptive names">
    Give each API key a clear, descriptive name that identifies its purpose and the application or environment using it (e.g., "Production Web Server", "Staging Environment", "CI/CD Pipeline").
  </Accordion>

  <Accordion title="Rotate keys periodically">
    Establish a key rotation schedule. Create a new key, update your applications to use it, then revoke the old key. This limits the window of exposure if a key is compromised.
  </Accordion>

  <Accordion title="Monitor API key usage">
    Review your API request logs regularly to detect unusual patterns that might indicate a compromised key.
  </Accordion>
</AccordionGroup>

## Authentication Errors

### Missing API Key

If no API key is provided, you'll receive:

```json theme={null}
{
  "message": "API key is required."
}
```

**HTTP Status**: `401 Unauthorized`

### Invalid API Key

If the provided API key doesn't exist or has been revoked:

```json theme={null}
{
  "message": "Invalid API key."
}
```

**HTTP Status**: `401 Unauthorized`

### IP Not Allowed

If the request comes from an IP address not in the key's whitelist:

```json theme={null}
{
  "message": "Access denied. Your IP address is not allowed."
}
```

**HTTP Status**: `403 Forbidden`

## API Endpoints

The following endpoints are available when authenticated with an API key:

| Endpoint                           | Method | Description                |
| ---------------------------------- | ------ | -------------------------- |
| `/api/emails`                      | POST   | Send an email              |
| `/api/emails`                      | GET    | List sent emails           |
| `/api/emails/{requestId}`          | GET    | Get email details          |
| `/api/templates`                   | GET    | List templates             |
| `/api/templates`                   | POST   | Create a template          |
| `/api/templates/{slug}`            | GET    | Get template details       |
| `/api/templates/{slug}`            | PUT    | Update a template          |
| `/api/templates/{slug}`            | DELETE | Delete a template          |
| `/api/templates/{slug}/merge-tags` | GET    | Get template merge tags    |
| `/api/templates/html`              | GET    | Get rendered template HTML |
| `/api/projects`                    | GET    | List projects              |
| `/api/domains`                     | GET    | List domains               |
| `/api/domains`                     | POST   | Create a domain            |
| `/api/domains/{domain}`            | GET    | Get domain details         |
| `/api/domains/{domain}/verify`     | POST   | Verify a domain            |
| `/api/domains/{domain}`            | DELETE | Delete a domain            |
| `/api/webhooks`                    | GET    | List webhooks              |
| `/api/webhooks/{webhookId}`        | GET    | Get webhook details        |
| `/api/health`                      | GET    | Health check               |
| `/api/auth/check`                  | GET    | Verify API key validity    |

## Next Steps

<CardGroup cols={2}>
  <Card title="Permissions" icon="shield-check" href="/learn/api-keys/permissions">
    Learn more about API key permission levels and how to configure them
  </Card>

  <Card title="Sandbox API Keys" icon="flask-vial" href="/learn/api-keys/sandbox">
    Test your integration safely without sending to real recipients
  </Card>

  <Card title="Send Your First Email" icon="paper-plane" href="/quickstart/php/introduction">
    Get started with sending emails using your API key
  </Card>
</CardGroup>
