# Python

Call Formerie from any Python server with `requests`, the client most projects already have. You don't need a Formerie package or an API key: a form's public address is all it takes.

## Submit a form

Install `requests`, save this as `submit.py`, and run `python submit.py`.

```bash
pip install requests
```

```python
import os

import requests

RUNTIME_URL = os.environ.get("FORMERIE_RUNTIME_URL", "https://forms.formerie.com")
# Your form. This is the only line that names it.
FORM = os.environ.get("FORMERIE_FORM", "acme/contact")

response = requests.post(
    f"{RUNTIME_URL}/{FORM}/submit",
    json={
        "fields": {
            "name": "Jane Example",
            "email": "jane@example.com",
            "message": "Hello from my server",
        },
    },
    timeout=10,
)
result = response.json()
print(response.status_code, result["submissionUid"] if result["ok"] else result["error"]["code"])
```

Replace `acme/contact`, on the marked line, with your own handles. A success is HTTP `202`, with a `submissionUid` such as `sub_p6dr8wq2j7tkan`: the answers are stored, and their email is queued. Each sample reads two optional settings from the environment, `FORMERIE_RUNTIME_URL` for a hostname you've connected, and `FORMERIE_FORM` for the handles.

## Before you start

1. [Publish a form](/guides/publish/), and take its workspace and form handles from the **Publish** tab. Your server doesn't need to be in the form's allowed websites.
2. To try things without emailing anyone, create a test key on the form's **Tests** tab, and put it in an environment variable called `FORMERIE_TEST_KEY`:

```python
import os

import requests

RUNTIME_URL = os.environ.get("FORMERIE_RUNTIME_URL", "https://forms.formerie.com")
# Your form. This is the only line that names it.
FORM = os.environ.get("FORMERIE_FORM", "acme/contact")

response = requests.post(
    f"{RUNTIME_URL}/{FORM}/submit",
    # Keep the key out of your code. A test is stored apart and emails nobody.
    headers={"X-Formerie-Test-Key": os.environ["FORMERIE_TEST_KEY"]},
    json={"fields": {"name": "Jane Example", "email": "jane@example.com", "message": "Just a test"}},
    timeout=10,
)
result = response.json()
print(response.status_code, result["submissionUid"] if result["ok"] else result["error"]["code"])
```

A test comes back as `tst_...`, is stored apart, and emails nobody. A wrong key gets `TEST_KEY_INVALID`, HTTP `401`, and nothing is stored. Remove the header before you go live, since a key left in place files everything as a test. See [Test from a server or CI](/guides/test-your-form/#test-from-a-server-or-ci).

## Check answers without submitting

`validate` checks answers and stores nothing, so you can flag a problem early. It answers `200` when they pass, and `422` with the same errors as a submission when they don't. The final submission always checks the whole form again.

```python
import os

import requests

RUNTIME_URL = os.environ.get("FORMERIE_RUNTIME_URL", "https://forms.formerie.com")
# Your form. This is the only line that names it.
FORM = os.environ.get("FORMERIE_FORM", "acme/contact")


def check_answers(fields, step=None):
    """Checks answers and stores nothing. Without a step, only the fields you send are checked."""
    body = {"mode": "step", "step": step, "fields": fields} if step else {"mode": "partial", "fields": fields}
    response = requests.post(f"{RUNTIME_URL}/{FORM}/validate", json=body, timeout=10)
    result = response.json()
    if result["ok"]:
        return {"valid": True, "values": result["values"]}
    if result["error"]["code"] != "VALIDATION_FAILED":
        raise RuntimeError(result["error"]["code"])
    return {"valid": False, "fields": result["error"]["fields"]}
```

By default, only the fields you send are checked. Pass a step to check every field in that step instead, on a form with [steps](/guides/multi-step-forms/). A step the form doesn't have gets `BAD_REQUEST`.

## Show errors per field

Answers that fail come back as `VALIDATION_FAILED`, HTTP `422`, and nothing is stored. `error.fields` holds the problems by field, and `error.issues` holds the same ones in order. Each has a `path`, a `code` to match on, and a `message` that's safe to show, in the form's language.

```python
import html
import os

import requests

RUNTIME_URL = os.environ.get("FORMERIE_RUNTIME_URL", "https://forms.formerie.com")
# Your form. This is the only line that names it.
FORM = os.environ.get("FORMERIE_FORM", "acme/contact")


def submit_answers(fields):
    response = requests.post(f"{RUNTIME_URL}/{FORM}/submit", json={"fields": fields}, timeout=10)
    return response.json()


def field_errors(result):
    """The messages for each field, by path, such as message or contact.email."""
    if result["ok"] or result["error"]["code"] != "VALIDATION_FAILED":
        return {}
    return {path: [issue["message"] for issue in issues] for path, issues in result["error"]["fields"].items()}


def answer_at(answers, path):
    """Finds the visitor's answer for a path, so the form can show it again."""
    value = answers
    for part in path.split("."):
        value = value.get(part, "") if isinstance(value, dict) else ""
    return value


def render_field(path, answers, errors):
    """One input with its answer kept and its first message under it."""
    name = html.escape(path)
    value = html.escape(str(answer_at(answers, path)))
    error = f'<p class="error">{html.escape(errors[path][0])}</p>' if path in errors else ""
    return f'<input name="{name}" value="{value}">{error}'
```

A field inside a group has a path such as `contact.email`, and one inside a list has `guests[0].email`, so split the path to find its answer. See [Field paths](/guides/validation/#field-paths). Show the visitor's answers again with the messages, escaped, so they only have to fix what's wrong.

## Retry safely

A network failure doesn't tell you whether the submission arrived. So send one `metadata.idempotencyKey` per submission, the same on every retry. Formerie then counts and delivers it once, and answers a repeat with `DUPLICATE_SUBMISSION`, HTTP `409`, which means the first one worked.

```python
import os
import random
import time
import uuid

import requests

RUNTIME_URL = os.environ.get("FORMERIE_RUNTIME_URL", "https://forms.formerie.com")
# Your form. This is the only line that names it.
FORM = os.environ.get("FORMERIE_FORM", "acme/contact")
MAX_ATTEMPTS = 3
LONGEST_WAIT = 30
TEMPORARY_CODES = {"FORM_MAINTENANCE", "QUEUE_FAILED", "INTERNAL_ERROR"}


def retry_after(response):
    value = response.headers.get("Retry-After", "")
    return int(value) if value.isdigit() else None


def send_once(fields, key):
    """One attempt. Says what happened, and whether another attempt could help."""
    try:
        response = requests.post(
            f"{RUNTIME_URL}/{FORM}/submit",
            json={"fields": fields, "metadata": {"idempotencyKey": key}},
            timeout=10,
        )
    except requests.RequestException:
        return {"outcome": "retry-later", "reason": "network", "again": True}

    after = retry_after(response)
    # Only the short-term limit sends Retry-After. A form's own limit can last an hour, so don't wait for it.
    if response.status_code == 429:
        return {"outcome": "retry-later", "reason": "rate-limited", "after": after,
                "again": after is not None and after <= LONGEST_WAIT}

    # Something in front of Formerie may answer without JSON, so look at the status first.
    try:
        result = response.json()
    except ValueError:
        return {"outcome": "retry-later", "reason": "bad-response", "again": response.status_code in (502, 503, 504)}

    if result["ok"]:
        return {"outcome": "accepted", "id": result["submissionUid"]}
    error = result["error"]
    if error["code"] == "DUPLICATE_SUBMISSION":
        # The first send worked, and only its answer was lost.
        return {"outcome": "accepted", "duplicate": True}
    if error["code"] in TEMPORARY_CODES:
        return {"outcome": "retry-later", "reason": error["code"], "again": True}
    if error["code"] == "VALIDATION_FAILED":
        return {"outcome": "invalid", "code": error["code"], "issues": error["issues"]}
    return {"outcome": "rejected", "code": error["code"], "message": error["message"]}


def submit_with_retries(fields, key=None):
    # One key per submission, the same on every retry. Store it with the answers if you retry later.
    key = key or str(uuid.uuid4())
    for attempt in range(1, MAX_ATTEMPTS + 1):
        answer = send_once(fields, key)
        if not answer.pop("again", False) or attempt == MAX_ATTEMPTS:
            return {**answer, "key": key, "attempts": attempt}
        backoff = random.uniform(0, min(0.25 * 2 ** attempt, 4))
        time.sleep(max(answer.get("after") or 0, backoff))
```

| Answer | Retry? |
| --- | --- |
| No connection, or a timeout | Yes, with the same key |
| `429` with `Retry-After` | Yes, after that wait, if it's short. The short-term limit answers with `Retry-After: 60` |
| `429` with no `Retry-After` | No. A form's own limit can last an hour, so ask the visitor to try again later |
| `FORM_MAINTENANCE`, `QUEUE_FAILED`, `INTERNAL_ERROR` | Yes, after a short wait |
| `502`, `503` or `504` with no JSON | Yes. Something in front of Formerie answered |
| Any other answer with no JSON | No. Keep the key, and look into it |
| `DUPLICATE_SUBMISSION` | No. Treat it as a success |
| `VALIDATION_FAILED` and any other code | No. The answer won't change |

- The key must be a non-empty string. Anything else is ignored, and there's no repeat check.
- A repeat is noticed for 300 seconds by default, under the form's repeat window. See [What the repeat window covers](/guides/spam-protection/#what-the-repeat-window-covers).
- The check comes first, so a key that went through gets `DUPLICATE_SUBMISSION` even with different answers. Use a new key for each new submission. A key refused for its answers was never accepted, so it can go again once they're fixed.
- A retry after `QUEUE_FAILED` can store a second copy, which you'd see under **Submissions**. It's rare.

## Human verification

If your form requires human verification, use your own keys, with your site in the provider's list of domains and in the form's allowed websites. The widget adds its token to your form. Forward two things:

1. **The token,** as `verificationToken`, taken out of the fields.
2. **The `Origin` of the visitor's request,** because Formerie compares the token's domain with it. A server sends none by itself, and the check then fails with `TURNSTILE_FAILED`.

```python
import os

import requests

RUNTIME_URL = os.environ.get("FORMERIE_RUNTIME_URL", "https://forms.formerie.com")
# Your form. This is the only line that names it.
FORM = os.environ.get("FORMERIE_FORM", "acme/contact")


def submit_verified(posted, origin):
    """posted is what your form sent. origin is the Origin header of the visitor's request."""
    fields = dict(posted)
    token = fields.pop("cf-turnstile-response", "")
    # Without the visitor's Origin, the provider's hostname can't match, and the check fails.
    headers = {"Origin": origin} if origin else {}
    response = requests.post(
        f"{RUNTIME_URL}/{FORM}/submit",
        headers=headers,
        json={"fields": fields, "verificationToken": token},
        timeout=10,
    )
    return response.json()
```

An `Origin` that isn't in the form's allowed websites gets `FORBIDDEN_ORIGIN`. Only forward it for this: on any other form, it turns on a check your server doesn't otherwise need. The widget needs JavaScript in the visitor's browser. See [Verification on the server path](/guides/framework-entry-points/#verification-on-the-server-path).

## Spam checks

Hosted pages and embeds send this metadata for you. From your server, send it yourself, or those checks are skipped.

```python
import os
import uuid
from datetime import datetime, timedelta, timezone

import requests

RUNTIME_URL = os.environ.get("FORMERIE_RUNTIME_URL", "https://forms.formerie.com")
# Your form. This is the only line that names it.
FORM = os.environ.get("FORMERIE_FORM", "acme/contact")


def submit_with_metadata(fields, started_at, visitor_id):
    response = requests.post(
        f"{RUNTIME_URL}/{FORM}/submit",
        json={
            "fields": fields,
            "metadata": {
                "idempotencyKey": str(uuid.uuid4()),
                # When the visitor opened the form, for the minimum submit time check.
                "startedAt": started_at.isoformat().replace("+00:00", "Z"),
                "pageUrl": "https://www.example.com/contact",
                # Your own visitor ID, for a limit rule with the deviceToken scope.
                "deviceToken": visitor_id,
            },
        },
        timeout=10,
    )
    return response.status_code, response.json()
```

| Field | What it's for |
| --- | --- |
| `idempotencyKey` | The repeat check, as above |
| `startedAt` | When the visitor opened the form, as an ISO 8601 time. Sent sooner than the form's minimum, 1 second by default, it gets `SPAM_REJECTED`. Keep the real time from when you showed the form, not the time of this call. One that can't be read skips the check |
| `pageUrl` | The page the form was sent from. Stored only if it's an http or https address |
| `deviceToken` | Your own visitor ID, for a limit per visitor, below |

The hidden field check runs when your form sends that field, and links and human verification run on the server either way. See [Spam and limits](/guides/spam-protection/).

## Limits from your server

Formerie counts visitors by network address, and from here, that's your server's. **Every visitor counts as your server.**

| Limit | Default | From your server |
| --- | --- | --- |
| Per visitor | 30 submissions every 10 minutes | Shared by all your visitors. Raise it before you launch, or leave it empty for no limit, under **Settings**, then **Submission limits** |
| Whole form | 1,000 submissions an hour | The same. On the Free plan, it's also the most a form can accept |
| Short-term | 120 requests a minute for each form from one address | Can't be changed. It's the only one that sends `Retry-After`. `validate` counts here too |

Over any of them, you get `RATE_LIMITED`, HTTP `429`. To keep a limit for each visitor, a rule with the `deviceToken` scope counts by the ID you send, such as a hash of the visitor's address. The app's settings don't offer that rule yet, so [talk to us](https://formerie.com/contact/) to set one up, and keep the whole-form limit, since anyone calling the form directly can change their ID. See [Limits on the server path](/guides/framework-entry-points/#limits-on-the-server-path) for the reasoning, and [Plans and limits](/guides/plans-and-limits/) for monthly counts.

## Django

This works through the API: the view reads the visitor's form, and calls Formerie with `requests`. It was run against a local Formerie backend with Django 6.1. It answers `202` with the submission's ID, the same status as Formerie with messages by field, or `503` when it can't reach Formerie. Keep Django's CSRF protection on, with `{% csrf_token %}` in your form.

```bash
pip install django requests
```

```python
import requests
from django.http import JsonResponse
from django.views.decorators.http import require_POST

FORMERIE_RUNTIME_URL = os.environ.get("FORMERIE_RUNTIME_URL", "https://forms.formerie.com")
# Your form. This is the only line that names it.
FORMERIE_FORM = os.environ.get("FORMERIE_FORM", "acme/contact")


@require_POST
def contact(request):
    # Name the fields you send, so a visitor can't add others.
    fields = {name: request.POST.get(name, "") for name in ("name", "email", "message")}
    try:
        answer = requests.post(f"{FORMERIE_RUNTIME_URL}/{FORMERIE_FORM}/submit", json={"fields": fields}, timeout=10)
        result = answer.json()
    except (requests.RequestException, ValueError):
        # No connection, a timeout, or an answer that isn't JSON. Keep the visitor's answers on screen.
        return JsonResponse({"code": "TRY_AGAIN"}, status=503)
    if result["ok"]:
        return JsonResponse({"id": result["submissionUid"]}, status=202)
    errors = {path: [issue["message"] for issue in issues] for path, issues in result["error"].get("fields", {}).items()}
    return JsonResponse({"code": result["error"]["code"], "errors": errors}, status=answer.status_code)
```

## Good to know

- `requests` has no timeout unless you set one, so keep `timeout=` on every call.
- Keep test keys and answers out of your logs. A `requestId` in an error, or the `X-Request-Id` header, is what to log and to quote when you ask for help.
- Match on `error.code`, never on the message, since a form can reword its messages and a status can cover several codes. [Error codes](/guides/error-codes/) lists them all.

| With | Note |
| --- | --- |
| Flask | Read answers from `request.form`, and the visitor's `Origin` from `request.headers`. Django is above. |
| FastAPI | `requests` blocks, so in an `async def` route use `httpx.AsyncClient`, which takes the same `json=` and `timeout=`, or a plain `def` route. |
| `httpx` | Works the same for these calls. Catch `httpx.HTTPError` in place of `requests.RequestException`. |

The routes, fields and every error are in the [API reference](/guides/api-reference/).
