> For the complete documentation index, see [llms.txt](https://help.delpha.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://help.delpha.io/delpha-api-and-mcp/api/code-examples.md).

# Code examples

The examples below call `POST /v1/email` and its batch form from a shell with `curl`, from Python and from Node.js. Every operation of this document also publishes its own samples in `x-codeSamples` — curl, Python, Node.js and the raw HTTP request — and the request bodies are the examples shown on each operation. Each example sends `dlp_live_your_key_here` where the API key goes. The curl examples run in a POSIX shell and generate each `Idempotency-Key` with `uuidgen`, which ships with macOS and many Linux distributions (Debian-based systems carry it in `uuid-runtime`); any unique string up to 255 printable ASCII characters is a valid key. The Python examples need the `requests` package (`pip install requests`), and the Node.js examples are CommonJS (save them as `.js` or `.cjs`) and use the built-in `fetch` of Node.js 18 or later.

#### Submit and poll

Every example calls `https://api.delpha.io`. `POST /v1/email` sends the request example published on the operation — `email`, `first_name`, `last_name` and `website` — and answers **202** with a `job_id` in the body and the `Location` and `Retry-After` headers. The loop then sends `GET /v1/email/{job_id}`, the request the poll operation's own sample describes, each time `Retry-After` seconds have passed, and branches on the HTTP status, reading `code` on a **504** only:

* **200** ends the loop with the result.
* **202** (the job is still running), **429** and **503** are waited out for the `Retry-After` the response carries, and the poll is sent again.
* **504** is waited out the same way unless its `code` is `job_timeout`, which the `Error` catalog defines as a job that will never complete; that ends the loop.
* Any other status ends the loop — **404** (no job for this id), **409** (the credit reservation expired before delivery) and **500** among them — and the last body is printed.

{% tabs %}
{% tab title="curl" %}

```bash
# The same key with the same body replays the first 202, with no second charge.
IDEMPOTENCY_KEY=$(uuidgen)

RESPONSE=$(curl -sS -i -X POST "https://api.delpha.io/v1/email" \
  -H "Authorization: Bearer dlp_live_your_key_here" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: $IDEMPOTENCY_KEY" \
  --data '{"email":"jordan.rivera@example.com","first_name":"Jordan","last_name":"Rivera","website":"https://delpha.io/"}')
# The API's status line is the last one: behind a proxy, curl -i prints the
# proxy's `200 Connection established` first.
STATUS=$(printf '%s\n' "$RESPONSE" | sed -n 's/^HTTP[^ ]* \([0-9]*\).*/\1/p' | tail -n 1)
echo "$STATUS"

if [ "$STATUS" = 202 ]; then
  JOB_ID=$(printf '%s\n' "$RESPONSE" | sed -n 's/.*"job_id": *"\([^"]*\)".*/\1/p')
  while :; do
    RETRY_AFTER=$(printf '%s\n' "$RESPONSE" | tr -d '\r' | sed -n 's/^[Rr]etry-[Aa]fter: *//p' | tail -n 1)
    sleep "${RETRY_AFTER:-1}"
    RESPONSE=$(curl -sS -i "https://api.delpha.io/v1/email/$JOB_ID" \
      -H "Authorization: Bearer dlp_live_your_key_here")
    STATUS=$(printf '%s\n' "$RESPONSE" | sed -n 's/^HTTP[^ ]* \([0-9]*\).*/\1/p' | tail -n 1)
    case "$STATUS" in
      202 | 429 | 503) ;;
      504) printf '%s\n' "$RESPONSE" | grep -q '"code": *"job_timeout"' && break ;;
      *) break ;;
    esac
  done
  echo "$STATUS"
fi

# The body is the last line of the output.
printf '%s\n' "$RESPONSE" | tail -n 1
```

{% endtab %}

{% tab title="Python" %}

```python
import time
import uuid

import requests

# Statuses after which the same poll is sent again once `Retry-After` seconds have
# passed. A 504 is one of them unless its `code` is `job_timeout`.
WAIT_STATUSES = {202, 429, 503, 504}


# The JSON body, or the raw text when the body is not JSON.
def read_body(response):
    try:
        return response.json()
    except ValueError:
        return response.text


payload = {
    "email": "jordan.rivera@example.com",
    "first_name": "Jordan",
    "last_name": "Rivera",
    "website": "https://delpha.io/",
}
# The same key with the same body replays the first 202, with no second charge.
idempotency_key = str(uuid.uuid4())

response = requests.post(
    "https://api.delpha.io/v1/email",
    headers={
        "Authorization": "Bearer dlp_live_your_key_here",
        "Idempotency-Key": idempotency_key,
    },
    json=payload,
    timeout=30,
)
print(response.status_code)
body = read_body(response)

if response.status_code == 202:
    job_id = body["job_id"]
    while response.status_code in WAIT_STATUSES:
        time.sleep(int(response.headers.get("Retry-After", "1")))
        response = requests.get(
            f"https://api.delpha.io/v1/email/{job_id}",
            headers={
                "Authorization": "Bearer dlp_live_your_key_here",
            },
            timeout=30,
        )
        body = read_body(response)
        if (
            response.status_code == 504
            and isinstance(body, dict)
            and body.get("code") == "job_timeout"
        ):
            break
    print(response.status_code)

print(body)
```

{% endtab %}

{% tab title="Node.js" %}

```javascript
const { randomUUID } = require("node:crypto");

// Statuses after which the same poll is sent again once `Retry-After` seconds have
// passed. A 504 is one of them unless its `code` is `job_timeout`.
const WAIT_STATUSES = new Set([202, 429, 503, 504]);

function sleep(seconds) {
  return new Promise((resolve) => setTimeout(resolve, seconds * 1000));
}

// The JSON body, or the raw text when the body is not JSON.
async function readBody(response) {
  const text = await response.text();
  try {
    return JSON.parse(text);
  } catch {
    return text;
  }
}

async function main() {
  const payload = {
    "email": "jordan.rivera@example.com",
    "first_name": "Jordan",
    "last_name": "Rivera",
    "website": "https://delpha.io/"
  };
  // The same key with the same body replays the first 202, with no second charge.
  const idempotencyKey = randomUUID();
  const response = await fetch("https://api.delpha.io/v1/email", {
    method: "POST",
    headers: {
      "Authorization": "Bearer dlp_live_your_key_here",
      "Content-Type": "application/json",
      "Idempotency-Key": idempotencyKey,
    },
    body: JSON.stringify(payload),
  });
  console.log(response.status);
  let last = response;
  let body = await readBody(response);

  if (response.status === 202) {
    const jobId = body.job_id;
    while (WAIT_STATUSES.has(last.status)) {
      await sleep(Number(last.headers.get("Retry-After") ?? 1));
      const response = await fetch(`https://api.delpha.io/v1/email/${jobId}`, {
        headers: {
          "Authorization": "Bearer dlp_live_your_key_here",
        },
      });
      last = response;
      body = await readBody(response);
      if (response.status === 504 && body?.code === "job_timeout") {
        break;
      }
    }
    console.log(last.status);
  }

  console.log(typeof body === "string" ? body : JSON.stringify(body, null, 2));
}

main();
```

{% endtab %}
{% endtabs %}

#### Idempotent submit

The same `POST /v1/email`, sent twice with one `Idempotency-Key` and the same body. Both answers are **202** with the same `job_id`; the second carries `Idempotent-Replayed: true`, starts no new job and adds no charge. A key is honoured for 24 hours and is scoped to the team; the same key with a different body answers **409** `idempotency_key_reuse` (see **Idempotency**).

{% tabs %}
{% tab title="curl" %}

```bash
# The same key with the same body replays the first 202, with no second charge.
IDEMPOTENCY_KEY=$(uuidgen)

# The second answer carries `Idempotent-Replayed: true` and the first answer's job_id.
for ATTEMPT in first second; do
  echo "$ATTEMPT request:"
  curl -i -X POST "https://api.delpha.io/v1/email" \
    -H "Authorization: Bearer dlp_live_your_key_here" \
    -H "Content-Type: application/json" \
    -H "Idempotency-Key: $IDEMPOTENCY_KEY" \
    --data '{"email":"jordan.rivera@example.com","first_name":"Jordan","last_name":"Rivera","website":"https://delpha.io/"}'
  echo
done
```

{% endtab %}

{% tab title="Python" %}

```python
import uuid

import requests

payload = {
    "email": "jordan.rivera@example.com",
    "first_name": "Jordan",
    "last_name": "Rivera",
    "website": "https://delpha.io/",
}
# The same key with the same body replays the first 202, with no second charge.
idempotency_key = str(uuid.uuid4())

# The second answer carries `Idempotent-Replayed: true` and the first answer's job_id.
for attempt in ("first", "second"):
    response = requests.post(
        "https://api.delpha.io/v1/email",
        headers={
            "Authorization": "Bearer dlp_live_your_key_here",
            "Idempotency-Key": idempotency_key,
        },
        json=payload,
        timeout=30,
    )
    print(attempt, response.status_code)
    print(response.headers.get("Idempotent-Replayed"))
    print(response.json().get("job_id"))
```

{% endtab %}

{% tab title="Node.js" %}

```javascript
const { randomUUID } = require("node:crypto");

async function main() {
  const payload = {
    "email": "jordan.rivera@example.com",
    "first_name": "Jordan",
    "last_name": "Rivera",
    "website": "https://delpha.io/"
  };
  // The same key with the same body replays the first 202, with no second charge.
  const idempotencyKey = randomUUID();
  // The second answer carries `Idempotent-Replayed: true` and the first answer's job_id.
  for (const attempt of ["first", "second"]) {
    const response = await fetch("https://api.delpha.io/v1/email", {
      method: "POST",
      headers: {
        "Authorization": "Bearer dlp_live_your_key_here",
        "Content-Type": "application/json",
        "Idempotency-Key": idempotencyKey,
      },
      body: JSON.stringify(payload),
    });
    console.log(attempt, response.status);
    console.log(response.headers.get("Idempotent-Replayed"));
    console.log((await response.json()).job_id);
  }
}

main();
```

{% endtab %}
{% endtabs %}

#### Batch

`POST /v1/email/batch` sends the batch request example — an `items` list of 1 record — as one job, and the same loop polls `GET /v1/email/batch/{job_id}`. Its **200** carries `counts` (the per-item totals), `result_url` (a presigned link to the result file) and, when that file is 1 MB or smaller, the results inline as `result_data`. Only the items that succeed are charged (see **Batch operations**).

{% tabs %}
{% tab title="curl" %}

```bash
# The same key with the same body replays the first 202, with no second charge.
IDEMPOTENCY_KEY=$(uuidgen)

RESPONSE=$(curl -sS -i -X POST "https://api.delpha.io/v1/email/batch" \
  -H "Authorization: Bearer dlp_live_your_key_here" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: $IDEMPOTENCY_KEY" \
  --data '{"items":[{"email":"jordan.rivera@example.com","first_name":"Jordan","last_name":"Rivera","website":"https://delpha.io/"}]}')
# The API's status line is the last one: behind a proxy, curl -i prints the
# proxy's `200 Connection established` first.
STATUS=$(printf '%s\n' "$RESPONSE" | sed -n 's/^HTTP[^ ]* \([0-9]*\).*/\1/p' | tail -n 1)
echo "$STATUS"

if [ "$STATUS" = 202 ]; then
  JOB_ID=$(printf '%s\n' "$RESPONSE" | sed -n 's/.*"job_id": *"\([^"]*\)".*/\1/p')
  while :; do
    RETRY_AFTER=$(printf '%s\n' "$RESPONSE" | tr -d '\r' | sed -n 's/^[Rr]etry-[Aa]fter: *//p' | tail -n 1)
    sleep "${RETRY_AFTER:-1}"
    RESPONSE=$(curl -sS -i "https://api.delpha.io/v1/email/batch/$JOB_ID" \
      -H "Authorization: Bearer dlp_live_your_key_here")
    STATUS=$(printf '%s\n' "$RESPONSE" | sed -n 's/^HTTP[^ ]* \([0-9]*\).*/\1/p' | tail -n 1)
    case "$STATUS" in
      202 | 429 | 503) ;;
      504) printf '%s\n' "$RESPONSE" | grep -q '"code": *"job_timeout"' && break ;;
      *) break ;;
    esac
  done
  echo "$STATUS"
fi

# The body is the last line of the output.
printf '%s\n' "$RESPONSE" | tail -n 1
```

{% endtab %}

{% tab title="Python" %}

```python
import time
import uuid

import requests

# Statuses after which the same poll is sent again once `Retry-After` seconds have
# passed. A 504 is one of them unless its `code` is `job_timeout`.
WAIT_STATUSES = {202, 429, 503, 504}


# The JSON body, or the raw text when the body is not JSON.
def read_body(response):
    try:
        return response.json()
    except ValueError:
        return response.text


payload = {
    "items": [
        {
            "email": "jordan.rivera@example.com",
            "first_name": "Jordan",
            "last_name": "Rivera",
            "website": "https://delpha.io/",
        },
    ],
}
# The same key with the same body replays the first 202, with no second charge.
idempotency_key = str(uuid.uuid4())

response = requests.post(
    "https://api.delpha.io/v1/email/batch",
    headers={
        "Authorization": "Bearer dlp_live_your_key_here",
        "Idempotency-Key": idempotency_key,
    },
    json=payload,
    timeout=30,
)
print(response.status_code)
body = read_body(response)

if response.status_code == 202:
    job_id = body["job_id"]
    while response.status_code in WAIT_STATUSES:
        time.sleep(int(response.headers.get("Retry-After", "1")))
        response = requests.get(
            f"https://api.delpha.io/v1/email/batch/{job_id}",
            headers={
                "Authorization": "Bearer dlp_live_your_key_here",
            },
            timeout=30,
        )
        body = read_body(response)
        if (
            response.status_code == 504
            and isinstance(body, dict)
            and body.get("code") == "job_timeout"
        ):
            break
    print(response.status_code)

if response.status_code == 200:
    print(body["counts"])
    print(body["result_url"])
    # Inline only when the result file is 1 MB or smaller.
    print(body.get("result_data"))
else:
    print(body)
```

{% endtab %}

{% tab title="Node.js" %}

```javascript
const { randomUUID } = require("node:crypto");

// Statuses after which the same poll is sent again once `Retry-After` seconds have
// passed. A 504 is one of them unless its `code` is `job_timeout`.
const WAIT_STATUSES = new Set([202, 429, 503, 504]);

function sleep(seconds) {
  return new Promise((resolve) => setTimeout(resolve, seconds * 1000));
}

// The JSON body, or the raw text when the body is not JSON.
async function readBody(response) {
  const text = await response.text();
  try {
    return JSON.parse(text);
  } catch {
    return text;
  }
}

async function main() {
  const payload = {
    "items": [
      {
        "email": "jordan.rivera@example.com",
        "first_name": "Jordan",
        "last_name": "Rivera",
        "website": "https://delpha.io/"
      }
    ]
  };
  // The same key with the same body replays the first 202, with no second charge.
  const idempotencyKey = randomUUID();
  const response = await fetch("https://api.delpha.io/v1/email/batch", {
    method: "POST",
    headers: {
      "Authorization": "Bearer dlp_live_your_key_here",
      "Content-Type": "application/json",
      "Idempotency-Key": idempotencyKey,
    },
    body: JSON.stringify(payload),
  });
  console.log(response.status);
  let last = response;
  let body = await readBody(response);

  if (response.status === 202) {
    const jobId = body.job_id;
    while (WAIT_STATUSES.has(last.status)) {
      await sleep(Number(last.headers.get("Retry-After") ?? 1));
      const response = await fetch(`https://api.delpha.io/v1/email/batch/${jobId}`, {
        headers: {
          "Authorization": "Bearer dlp_live_your_key_here",
        },
      });
      last = response;
      body = await readBody(response);
      if (response.status === 504 && body?.code === "job_timeout") {
        break;
      }
    }
    console.log(last.status);
  }

  if (last.status === 200) {
    console.log(JSON.stringify(body.counts));
    console.log(body.result_url);
    // Inline only when the result file is 1 MB or smaller.
    console.log(JSON.stringify(body.result_data ?? null, null, 2));
  } else {
    console.log(typeof body === "string" ? body : JSON.stringify(body, null, 2));
  }
}

main();
```

{% endtab %}
{% endtabs %}

#### Calling in test mode

The submit and one poll, sent with a key created in test mode at **Developer → API keys** in place of the placeholder; nothing in a credential tells its mode. Every response the API renders to a test-mode call carries `X-Delpha-Mode: sandbox`, and a live response carries no such header, so the example prints that header from both answers. As the **Test mode** section states, a test-mode job is complete the moment it is accepted: the first poll answers **200** with the result rather than the transient **202**, the result comes from the published table of canned results, and no credit is reserved.

{% tabs %}
{% tab title="curl" %}

```bash
# The same key with the same body replays the first 202, with no second charge.
IDEMPOTENCY_KEY=$(uuidgen)

RESPONSE=$(curl -sS -i -X POST "https://api.delpha.io/v1/email" \
  -H "Authorization: Bearer dlp_live_your_key_here" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: $IDEMPOTENCY_KEY" \
  --data '{"email":"jordan.rivera@example.com","first_name":"Jordan","last_name":"Rivera","website":"https://delpha.io/"}')
# The status line, then `X-Delpha-Mode: sandbox` on a test-mode key (absent on a live one).
printf '%s\n' "$RESPONSE" | tr -d '\r' | grep -i -e '^HTTP' -e '^x-delpha-mode:'

JOB_ID=$(printf '%s\n' "$RESPONSE" | sed -n 's/.*"job_id": *"\([^"]*\)".*/\1/p')
RETRY_AFTER=$(printf '%s\n' "$RESPONSE" | tr -d '\r' | sed -n 's/^[Rr]etry-[Aa]fter: *//p' | tail -n 1)
sleep "${RETRY_AFTER:-1}"
RESPONSE=$(curl -sS -i "https://api.delpha.io/v1/email/$JOB_ID" \
  -H "Authorization: Bearer dlp_live_your_key_here")
printf '%s\n' "$RESPONSE" | tr -d '\r' | grep -i -e '^HTTP' -e '^x-delpha-mode:'
printf '%s\n' "$RESPONSE" | tail -n 1
```

{% endtab %}

{% tab title="Python" %}

```python
import time
import uuid

import requests

payload = {
    "email": "jordan.rivera@example.com",
    "first_name": "Jordan",
    "last_name": "Rivera",
    "website": "https://delpha.io/",
}
# The same key with the same body replays the first 202, with no second charge.
idempotency_key = str(uuid.uuid4())

response = requests.post(
    "https://api.delpha.io/v1/email",
    headers={
        "Authorization": "Bearer dlp_live_your_key_here",
        "Idempotency-Key": idempotency_key,
    },
    json=payload,
    timeout=30,
)
# `sandbox` on a test-mode key, `None` on a live one.
print(response.status_code, response.headers.get("X-Delpha-Mode"))
job_id = response.json()["job_id"]

time.sleep(int(response.headers.get("Retry-After", "1")))
response = requests.get(
    f"https://api.delpha.io/v1/email/{job_id}",
    headers={
        "Authorization": "Bearer dlp_live_your_key_here",
    },
    timeout=30,
)
print(response.status_code, response.headers.get("X-Delpha-Mode"))
print(response.json())
```

{% endtab %}

{% tab title="Node.js" %}

```javascript
const { randomUUID } = require("node:crypto");

function sleep(seconds) {
  return new Promise((resolve) => setTimeout(resolve, seconds * 1000));
}

async function poll(jobId) {
  const response = await fetch(`https://api.delpha.io/v1/email/${jobId}`, {
    headers: {
      "Authorization": "Bearer dlp_live_your_key_here",
    },
  });
  console.log(response.status, response.headers.get("X-Delpha-Mode"));
  console.log(JSON.stringify(await response.json(), null, 2));
}

async function main() {
  const payload = {
    "email": "jordan.rivera@example.com",
    "first_name": "Jordan",
    "last_name": "Rivera",
    "website": "https://delpha.io/"
  };
  // The same key with the same body replays the first 202, with no second charge.
  const idempotencyKey = randomUUID();
  const response = await fetch("https://api.delpha.io/v1/email", {
    method: "POST",
    headers: {
      "Authorization": "Bearer dlp_live_your_key_here",
      "Content-Type": "application/json",
      "Idempotency-Key": idempotencyKey,
    },
    body: JSON.stringify(payload),
  });
  // `sandbox` on a test-mode key, `null` on a live one.
  console.log(response.status, response.headers.get("X-Delpha-Mode"));
  const jobId = (await response.json()).job_id;

  await sleep(Number(response.headers.get("Retry-After") ?? 1));
  await poll(jobId);
}

main();
```

{% endtab %}
{% endtabs %}

#### Errors and webhooks

Every `code` an error body can carry is defined in the `code` enum of the `Error` schema: its meaning, the status it usually rides on, and whether a later attempt can succeed (see **Errors**). The gateway's own **401**, **403** and shared-floor **429** carry a `GatewayError` body with no `code`, which is why the loops above branch on the status.

A subscriber to the job lifecycle events is notified when a job finishes instead of polling for it, then fetches the result with one GET on the poll URL — events never carry the result. The Python and Node.js snippets that check the `Delpha-Signature` of each delivery are in the **Webhooks** section, under *Verifying a delivery*, and on the [Webhooks](https://help.delpha.io/delpha-api-and-mcp/api/webhooks) page.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://help.delpha.io/delpha-api-and-mcp/api/code-examples.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
