# Check endpoint

> The one endpoint. Send an IP address, an email address, or both, and get the signals for each.

`GET /v1/check`
`POST /v1/check`

Base URL:

```txt
https://heimdal.codebrewerz.com/api
```

Both methods do the same thing. `GET` takes its input from the query string, `POST` from a JSON body. Prefer `POST` in production: query strings tend to end up in access logs along the way, and a body keeps email addresses out of them.

## Request

### Headers

| Header          | Description                                                                                  |
| --------------- | -------------------------------------------------------------------------------------------- |
| `Authorization` | `Bearer hd_…`. Required unless you send `x-api-key`. See [Authentication](https://heimdal.codebrewerz.com/docs/authentication/). |
| `x-api-key`     | The key on its own. An alternative to `Authorization`.                                       |
| `Content-Type`  | `POST` only. Send `application/json`. The body is parsed as JSON whatever this header says.  |

### Parameters

Query parameters on `GET`, fields of the JSON object on `POST`. Send at least one of the two.

| Field   | Type   | Description                                                                          |
| ------- | ------ | ------------------------------------------------------------------------------------ |
| `ip`    | string | The visitor's IPv4 or IPv6 address. One address: no port, no CIDR range, no zone id. |
| `email` | string | The email address the visitor typed.                                                 |

- Each value may be at most 320 characters.
- Surrounding whitespace is trimmed. An empty string and a JSON `null` both count as "not sent".
- `ip` accepts IPv4-mapped IPv6 (`::ffff:203.0.113.7`) and looks it up as the IPv4 address it wraps.
- `email` needs a domain with at least one dot after the last `@`. Internationalised domains are accepted. Heimdal looks at the domain only and does not validate the part before the `@`.
- Fields other than `ip` and `email` are ignored.
- On `GET`, URL-encode the values. A literal `+` in a query string means a space, so `name+tag@example.com` must be sent as `name%2Btag@example.com`.

:::tip
If the IP address you have might be malformed (a header you do not control, the string `unknown`), validate it first or leave it out. An invalid `ip` fails the whole request with `400`, and you lose the email check with it.
:::

### Examples

`POST` with a JSON body:

**curl**

```sh
curl -X POST "https://heimdal.codebrewerz.com/api/v1/check" \
  -H "Authorization: Bearer $HEIMDAL_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"ip":"185.220.101.1","email":"test@mailinator.com"}'
```

**Node (fetch)**

```js
const response = await fetch("https://heimdal.codebrewerz.com/api/v1/check", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.HEIMDAL_API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ ip: "185.220.101.1", email: "test@mailinator.com" }),
  signal: AbortSignal.timeout(2000),
});

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

**Node (axios)**

```js
import axios from "axios";

const { data } = await axios.post(
  "https://heimdal.codebrewerz.com/api/v1/check",
  { ip: "185.220.101.1", 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.post(
    "https://heimdal.codebrewerz.com/api/v1/check",
    json={"ip": "185.220.101.1", "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"))
            .timeout(Duration.ofSeconds(2))
            .header("Authorization", "Bearer " + key)
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString("{\"ip\":\"185.220.101.1\",\"email\":\"test@mailinator.com\"}"))
            .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
        .post("https://heimdal.codebrewerz.com/api/v1/check")
        .bearer_auth(&key)
        .json(&serde_json::json!({"ip":"185.220.101.1","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"
	"strings"
	"time"
)

func main() {
	client := &http.Client{Timeout: 2 * time.Second}
	req, err := http.NewRequest("POST", "https://heimdal.codebrewerz.com/api/v1/check", strings.NewReader(`{"ip":"185.220.101.1","email":"test@mailinator.com"}`))
	if err != nil {
		panic(err)
	}
	req.Header.Set("Authorization", "Bearer "+os.Getenv("HEIMDAL_API_KEY"))
	req.Header.Set("Content-Type", "application/json")

	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->post("https://heimdal.codebrewerz.com/api/v1/check", [
    'headers' => ['Authorization' => 'Bearer ' . getenv('HEIMDAL_API_KEY')],
    'json' => ['ip' => "185.220.101.1", 'email' => "test@mailinator.com"],
]);

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

`GET` with query parameters:

**curl**

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

**Node (fetch)**

```js
const response = await fetch("https://heimdal.codebrewerz.com/api/v1/check?ip=185.220.101.1&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: { ip: "185.220.101.1", 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={"ip": "185.220.101.1", "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?ip=185.220.101.1&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(&[("ip", "185.220.101.1"), ("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?ip=185.220.101.1&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' => ['ip' => "185.220.101.1", 'email' => "test@mailinator.com"],
]);

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

## Response

A successful check answers `200` with a JSON object.

```json
{
  "block": true,
  "reasons": ["disposable_email", "tor", "vpn", "bad_isp"],
  "email": {
    "address": "test@mailinator.com",
    "domain": "mailinator.com",
    "disposable": true
  },
  "ip": {
    "address": "185.220.101.1",
    "tor": true,
    "vpn": true,
    "proxy": false,
    "bad_isp": true,
    "asn": 60729,
    "isp": "TORSERVERS-NET Stiftung Erneuerbare Freiheit"
  },
  "custom": { "matched": [] }
}
```

### Fields

| Field                    | Type             | Description                                                                                                                             |
| ------------------------ | ---------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| `block`                  | boolean          | `true` when `reasons` is not empty.                                                                                                     |
| `reasons`                | string[]         | The signals that fired, always in this order: `disposable_email`, `tor`, `proxy`, `vpn`, `bad_isp`, `custom_list`. Empty when none did. |
| `email`                  | object or `null` | `null` when you sent no `email`.                                                                                                        |
| `email.address`          | string           | The address as Heimdal compared it: trimmed, lowercased, with the domain in its ASCII form.                                             |
| `email.domain`           | string           | The part after the last `@`, lowercased. An internationalised domain is in its ASCII (`xn--`) form.                                     |
| `email.disposable`       | boolean          | The domain, or a parent of it, is on the disposable-domain list, or its mail servers belong to a known disposable provider.             |
| `ip`                     | object or `null` | `null` when you sent no `ip`.                                                                                                           |
| `ip.address`             | string           | The address as you sent it, trimmed.                                                                                                    |
| `ip.tor`                 | boolean          | The address is a Tor exit node.                                                                                                         |
| `ip.vpn`                 | boolean          | The address belongs to a VPN provider's network.                                                                                        |
| `ip.proxy`               | boolean          | The address is on the open-proxy list.                                                                                                  |
| `ip.bad_isp`             | boolean          | The address belongs to a hosting, datacenter or VPN network. Always `true` when `ip.vpn` is.                                            |
| `ip.asn`                 | number or `null` | The number of the network (autonomous system) that announces the address. `null` when no network does, as for private addresses.        |
| `ip.isp`                 | string or `null` | That network's name. `null` when unknown.                                                                                               |
| `custom`                 | object           | Always present.                                                                                                                         |
| `custom.matched`         | array            | The entries on your [custom lists](https://heimdal.codebrewerz.com/docs/custom-lists/) that this check hit.                                                                 |
| `custom.matched[].list`  | string           | The name of the list that holds the entry.                                                                                              |
| `custom.matched[].kind`  | string           | `email`, `domain`, `ip` or `cidr`.                                                                                                      |
| `custom.matched[].value` | string           | The entry as stored.                                                                                                                    |

[Signals explained](https://heimdal.codebrewerz.com/docs/reference/signals/) describes how each signal is decided.

### TypeScript

There is no SDK. If you want the response typed, this is the whole of it:

```ts
type CheckResult = {
  block: boolean;
  reasons: (
    "disposable_email" | "tor" | "proxy" | "vpn" | "bad_isp" | "custom_list"
  )[];
  email: { address: string; domain: string; disposable: boolean } | null;
  ip: {
    address: string;
    tor: boolean;
    vpn: boolean;
    proxy: boolean;
    bad_isp: boolean;
    asn: number | null;
    isp: string | null;
  } | null;
  custom: {
    matched: {
      list: string;
      kind: "email" | "domain" | "ip" | "cidr";
      value: string;
    }[];
  };
};
```

### Sending one value

A value you leave out comes back as `null`, and its signals cannot fire. This is the answer to a check with only an `email`:

```json
{
  "block": false,
  "reasons": [],
  "email": {
    "address": "ada@example.com",
    "domain": "example.com",
    "disposable": false
  },
  "ip": null,
  "custom": { "matched": [] }
}
```

### Response headers

| Header                           | Sent                                                                                                                                                                                                               |
| -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `Cache-Control: no-store`        | On every response. The lists change, so an answer should not be reused.                                                                                                                                            |
| `Heimdal-Degraded: custom_lists` | On a `200` when your custom lists could not be read. The signals are valid, but `custom.matched` is empty and `custom_list` is missing from `reasons`.                                                             |
| `Retry-After`                    | On a `429`, in seconds: `1` when the key went over its per-second limit, up to `60` when the address sent too many requests with a missing or invalid key. On a `503` while Heimdal restarts: `5`. |

## Errors

Errors answer with a `4xx` or `5xx` status and this body:

```json
{
  "error": {
    "code": "invalid_ip",
    "message": "`ip` must be one IPv4 or IPv6 address, without a port or zone."
  }
}
```

Every code is listed in [Errors and limits](https://heimdal.codebrewerz.com/docs/reference/errors/).
