# Authentication

> Every request carries an API key. Keys start with hd_, belong to one account, and must stay on your server.

## Create a key

In the [dashboard](https://heimdal.codebrewerz.com), open **API keys** and create a key. The full key is shown once, when you create it. If you lose it, create a new one and revoke the old one.

Keys start with `hd_`. A key belongs to your account and works while the account's subscription is active: every call checks emails and IP addresses, matches your [custom lists](https://heimdal.codebrewerz.com/docs/custom-lists/) and counts toward your analytics.

## Send the key

Send the key in the `Authorization` header as a bearer token:

```http
Authorization: Bearer hd_your_key
```

If your HTTP client makes that awkward, the `x-api-key` header works the same way:

```http
x-api-key: hd_your_key
```

When a request carries both, the bearer token is used.

**curl**

```sh
curl "https://heimdal.codebrewerz.com/api/v1/check?email=test%40mailinator.com" \
  -H "Authorization: Bearer $HEIMDAL_API_KEY"
```

**Node (fetch)**

```js
const response = await fetch("https://heimdal.codebrewerz.com/api/v1/check?email=test%40mailinator.com", {
  headers: { Authorization: `Bearer ${process.env.HEIMDAL_API_KEY}` },
  signal: AbortSignal.timeout(2000),
});

console.log(await response.json());
```

**Node (axios)**

```js
import axios from "axios";

const { data } = await axios.get("https://heimdal.codebrewerz.com/api/v1/check", {
  params: { email: "test@mailinator.com" },
  headers: { Authorization: `Bearer ${process.env.HEIMDAL_API_KEY}` },
  timeout: 2000,
});

console.log(data);
```

**Python**

```python
import os

import requests

response = requests.get(
    "https://heimdal.codebrewerz.com/api/v1/check",
    params={"email": "test@mailinator.com"},
    headers={"Authorization": f"Bearer {os.environ['HEIMDAL_API_KEY']}"},
    timeout=2,
)

print(response.json())
```

**Java**

```java
// Java 11+, no dependencies.
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;

public class Check {
    public static void main(String[] args) throws Exception {
        String key = System.getenv("HEIMDAL_API_KEY");
        if (key == null || key.isBlank()) {
            throw new IllegalStateException("Set HEIMDAL_API_KEY");
        }
        HttpClient client = HttpClient.newBuilder()
            .connectTimeout(Duration.ofSeconds(2))
            .build();
        HttpRequest request = HttpRequest.newBuilder(URI.create("https://heimdal.codebrewerz.com/api/v1/check?email=test%40mailinator.com"))
            .timeout(Duration.ofSeconds(2))
            .header("Authorization", "Bearer " + key)
            .GET()
            .build();
        HttpResponse<String> response =
            client.send(request, HttpResponse.BodyHandlers.ofString());
        // 200: the check. Anything else: {"error":{"code","message"}}.
        System.out.println(response.statusCode() + " " + response.body());
    }
}
```

**Rust**

```rust
// Cargo.toml
// [dependencies]
// reqwest = { version = "0.13", features = ["json", "query"] }
// serde_json = "1"
// tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
use std::time::Duration;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let key = std::env::var("HEIMDAL_API_KEY")?;
    let client = reqwest::Client::builder()
        .timeout(Duration::from_secs(2))
        .build()?;
    let response = client
        .get("https://heimdal.codebrewerz.com/api/v1/check")
        .bearer_auth(&key)
        .query(&[("email", "test@mailinator.com")])
        .send()
        .await?;
    // 200: the check. Anything else: {"error":{"code","message"}}.
    let status = response.status();
    let answer: serde_json::Value = response.json().await?;
    println!("{status} {answer}");
    Ok(())
}
```

**Go**

```go
package main

import (
	"fmt"
	"io"
	"net/http"
	"os"
	"time"
)

func main() {
	client := &http.Client{Timeout: 2 * time.Second}
	req, err := http.NewRequest("GET", "https://heimdal.codebrewerz.com/api/v1/check?email=test%40mailinator.com", nil)
	if err != nil {
		panic(err)
	}
	req.Header.Set("Authorization", "Bearer "+os.Getenv("HEIMDAL_API_KEY"))

	res, err := client.Do(req)
	if err != nil {
		panic(err)
	}
	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)
	fmt.Println(string(body))
}
```

**PHP**

```php
<?php
// composer require guzzlehttp/guzzle
require 'vendor/autoload.php';

$client = new GuzzleHttp\Client(['timeout' => 2]);
$response = $client->get("https://heimdal.codebrewerz.com/api/v1/check", [
    'headers' => ['Authorization' => 'Bearer ' . getenv('HEIMDAL_API_KEY')],
    'query' => ['email' => "test@mailinator.com"],
]);

echo $response->getBody();
```

## Keep the key on your server

:::caution
Never call the check endpoint from a browser or a mobile app. Anyone can read a key that ships to a client, and use your subscription with it.
:::

The API is built for server-to-server calls. Cross-origin browser requests are refused: only the Heimdal dashboard's own origin is allowed by CORS.

- Store the key in an environment variable or a secret manager, not in source control.
- Use a separate key for each service and environment, so you can revoke one without touching the others.
- Each key has its own rate limit: 100 requests a second. See [Rate limits](https://heimdal.codebrewerz.com/docs/reference/rate-limits/).

## Revoke and rotate

Revoke a key in the dashboard under **API keys**.

:::note
Heimdal remembers a verified key for up to 60 seconds. A revoked key can keep working for that long, and a subscription change (a new one, one that ends) takes up to 60 seconds to reach the API.
:::

To rotate a key without downtime:

1. Create a new key.
2. Deploy it to your service.
3. Revoke the old key once nothing uses it.

## When authentication fails

| Status | Code                    | Meaning                                                       |
| ------ | ----------------------- | ------------------------------------------------------------- |
| `401`  | `missing_api_key`       | No key in `Authorization` or `x-api-key`.                     |
| `401`  | `invalid_api_key`       | The key does not exist or was revoked.                        |
| `402`  | `subscription_required` | The key is valid, but the account has no active subscription. |

If a renewal payment fails, the API keeps answering for 3 days so you can fix the payment method. After that it answers `402` until the subscription is active again.

The full list of errors is in [Errors and limits](https://heimdal.codebrewerz.com/docs/reference/errors/).
