# Rust

Call Formerie from any Rust server with `reqwest`, the client most async projects use, and `serde_json`. You don't need a Formerie package or an API key: a form's public address is all it takes.

## Submit a form

Add the crates, and put this in `src/main.rs`. `cargo run` sends it.

```bash
cargo add reqwest@0.12 --features json
cargo add serde_json
cargo add tokio --features macros,rt-multi-thread,time
```

```rust
use serde_json::{json, Value};
use std::{env, time::Duration};

#[tokio::main]
async fn main() -> Result<(), reqwest::Error> {
    let runtime_url = env::var("FORMERIE_RUNTIME_URL").unwrap_or("https://forms.formerie.com".into());
    // Your form. This is the only line that names it.
    let form = env::var("FORMERIE_FORM").unwrap_or("acme/contact".into());

    let client = reqwest::Client::builder().timeout(Duration::from_secs(10)).build()?;
    let response = client
        .post(format!("{runtime_url}/{form}/submit"))
        .json(&json!({
            "fields": {
                "name": "Jane Example",
                "email": "jane@example.com",
                "message": "Hello from my server",
            },
        }))
        .send()
        .await?;
    let status = response.status();
    let result: Value = response.json().await?;
    println!("{status} {}", result["submissionUid"].as_str().or(result["error"]["code"].as_str()).unwrap_or(""));
    Ok(())
}
```

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`:

```rust
use serde_json::{json, Value};
use std::{env, time::Duration};

#[tokio::main]
async fn main() -> Result<(), reqwest::Error> {
    let runtime_url = env::var("FORMERIE_RUNTIME_URL").unwrap_or("https://forms.formerie.com".into());
    // Your form. This is the only line that names it.
    let form = env::var("FORMERIE_FORM").unwrap_or("acme/contact".into());
    // Keep the key out of your code. A test is stored apart and emails nobody.
    let test_key = env::var("FORMERIE_TEST_KEY").expect("FORMERIE_TEST_KEY isn't set");

    let client = reqwest::Client::builder().timeout(Duration::from_secs(10)).build()?;
    let response = client
        .post(format!("{runtime_url}/{form}/submit"))
        .header("X-Formerie-Test-Key", test_key)
        .json(&json!({
            "fields": { "name": "Jane Example", "email": "jane@example.com", "message": "Just a test" },
        }))
        .send()
        .await?;
    let status = response.status();
    let result: Value = response.json().await?;
    println!("{status} {}", result["submissionUid"].as_str().or(result["error"]["code"].as_str()).unwrap_or(""));
    Ok(())
}
```

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.

```rust
use serde_json::{json, Value};
use std::{env, time::Duration};

/// Checks answers and stores nothing. With no step, only the fields you send are checked.
async fn check_answers(client: &reqwest::Client, fields: Value, step: Option<&str>) -> Result<Value, Box<dyn std::error::Error>> {
    let runtime_url = env::var("FORMERIE_RUNTIME_URL").unwrap_or("https://forms.formerie.com".into());
    // Your form. This is the only line that names it.
    let form = env::var("FORMERIE_FORM").unwrap_or("acme/contact".into());

    let body = match step {
        Some(step) => json!({ "mode": "step", "step": step, "fields": fields }),
        None => json!({ "mode": "partial", "fields": fields }),
    };
    let result: Value = client.post(format!("{runtime_url}/{form}/validate")).json(&body).send().await?.json().await?;
    if result["ok"] != true && result["error"]["code"] != "VALIDATION_FAILED" {
        return Err(format!("formerie: {}", result["error"]["code"]).into());
    }
    Ok(result)
}
```

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.

```rust
use serde_json::{json, Value};
use std::{env, time::Duration};

async fn submit_answers(client: &reqwest::Client, fields: &Value) -> Result<Value, reqwest::Error> {
    let runtime_url = env::var("FORMERIE_RUNTIME_URL").unwrap_or("https://forms.formerie.com".into());
    // Your form. This is the only line that names it.
    let form = env::var("FORMERIE_FORM").unwrap_or("acme/contact".into());
    client.post(format!("{runtime_url}/{form}/submit")).json(&json!({ "fields": fields })).send().await?.json().await
}

fn escape_html(text: &str) -> String {
    text.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;").replace('\'', "&#39;")
}

/// Finds the visitor's answer for a path such as contact.email, so the form can show it again.
fn answer_at<'a>(answers: &'a Value, path: &str) -> &'a str {
    path.split('.').fold(answers, |value, part| &value[part]).as_str().unwrap_or("")
}

/// One input with its answer kept and its first message under it.
fn render_field(path: &str, answers: &Value, result: &Value) -> String {
    let error = match result["error"]["fields"][path][0]["message"].as_str() {
        Some(message) => format!(r#"<p class="error">{}</p>"#, escape_html(message)),
        None => String::new(),
    };
    format!(r#"<input name="{}" value="{}">{error}"#, escape_html(path), escape_html(answer_at(answers, path)))
}
```

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.

```rust
use rand::Rng;
use serde_json::{json, Value};
use std::{env, time::Duration};

const MAX_ATTEMPTS: u32 = 3;
const LONGEST_WAIT: u64 = 30;

/// One attempt. Says what happened, and whether another attempt could help.
async fn send_once(client: &reqwest::Client, fields: &Value, key: &str) -> (Value, bool, Option<u64>) {
    let runtime_url = env::var("FORMERIE_RUNTIME_URL").unwrap_or("https://forms.formerie.com".into());
    // Your form. This is the only line that names it.
    let form = env::var("FORMERIE_FORM").unwrap_or("acme/contact".into());

    let response = client
        .post(format!("{runtime_url}/{form}/submit"))
        .json(&json!({ "fields": fields, "metadata": { "idempotencyKey": key } }))
        .send()
        .await;
    let response = match response {
        Ok(response) => response,
        Err(_) => return (json!({ "outcome": "retry-later", "reason": "network" }), true, None),
    };
    let status = response.status().as_u16();

    // Only the short-term limit sends Retry-After. A form's own limit can last an hour, so don't wait for it.
    if status == 429 {
        let after: Option<u64> = response.headers().get("Retry-After").and_then(|value| value.to_str().ok()?.parse().ok());
        let again = after.is_some_and(|seconds| seconds <= LONGEST_WAIT);
        return (json!({ "outcome": "retry-later", "reason": "rate-limited", "after": after }), again, after);
    }

    // Something in front of Formerie may answer without JSON, so look at the status first.
    let result: Value = match response.json().await {
        Ok(result) => result,
        Err(_) => {
            let again = matches!(status, 502 | 503 | 504);
            return (json!({ "outcome": "retry-later", "reason": "bad-response" }), again, None);
        }
    };

    if result["ok"] == true {
        return (json!({ "outcome": "accepted", "id": result["submissionUid"] }), false, None);
    }
    let error = &result["error"];
    match error["code"].as_str().unwrap_or("") {
        // The first send worked, and only its answer was lost.
        "DUPLICATE_SUBMISSION" => (json!({ "outcome": "accepted", "duplicate": true }), false, None),
        code @ ("FORM_MAINTENANCE" | "QUEUE_FAILED" | "INTERNAL_ERROR") => {
            (json!({ "outcome": "retry-later", "reason": code }), true, None)
        }
        "VALIDATION_FAILED" => (json!({ "outcome": "invalid", "code": error["code"], "issues": error["issues"] }), false, None),
        _ => (json!({ "outcome": "rejected", "code": error["code"], "message": error["message"] }), false, None),
    }
}

/// One key per submission, the same on every retry. Store it with the answers if you retry later.
async fn submit_with_retries(client: &reqwest::Client, fields: &Value, key: &str) -> Value {
    let mut attempt = 1;
    loop {
        let (mut answer, again, after) = send_once(client, fields, key).await;
        if !again || attempt == MAX_ATTEMPTS {
            answer["key"] = json!(key);
            answer["attempts"] = json!(attempt);
            return answer;
        }
        let backoff = rand::rng().random_range(0..=(250u64 << attempt).min(4_000));
        tokio::time::sleep(Duration::from_millis(backoff.max(after.unwrap_or(0) * 1_000))).await;
        attempt += 1;
    }
}
```

| 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`.

```rust
use serde_json::{json, Value};
use std::{env, time::Duration};

/// posted is what your form sent. origin is the Origin header of the visitor's request.
async fn submit_verified(client: &reqwest::Client, mut posted: Value, origin: &str) -> Result<Value, reqwest::Error> {
    let runtime_url = env::var("FORMERIE_RUNTIME_URL").unwrap_or("https://forms.formerie.com".into());
    // Your form. This is the only line that names it.
    let form = env::var("FORMERIE_FORM").unwrap_or("acme/contact".into());

    let token = posted.as_object_mut().and_then(|fields| fields.remove("cf-turnstile-response"));
    let mut request = client
        .post(format!("{runtime_url}/{form}/submit"))
        .json(&json!({ "fields": posted, "verificationToken": token }));
    // Without the visitor's Origin, the provider's hostname can't match, and the check fails.
    if !origin.is_empty() {
        request = request.header("Origin", origin);
    }
    request.send().await?.json().await
}
```

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.

```rust
use chrono::{DateTime, SecondsFormat, Utc};
use serde_json::{json, Value};
use std::{env, time::Duration};

async fn submit_with_metadata(
    client: &reqwest::Client,
    fields: &Value,
    started_at: DateTime<Utc>,
    visitor_id: &str,
) -> Result<Value, reqwest::Error> {
    let runtime_url = env::var("FORMERIE_RUNTIME_URL").unwrap_or("https://forms.formerie.com".into());
    // Your form. This is the only line that names it.
    let form = env::var("FORMERIE_FORM").unwrap_or("acme/contact".into());

    client
        .post(format!("{runtime_url}/{form}/submit"))
        .json(&json!({
            "fields": fields,
            "metadata": {
                "idempotencyKey": uuid::Uuid::new_v4().to_string(),
                // When the visitor opened the form, for the minimum submit time check.
                "startedAt": started_at.to_rfc3339_opts(SecondsFormat::Secs, true),
                "pageUrl": "https://www.example.com/contact",
                // Your own visitor ID, for a limit rule with the deviceToken scope.
                "deviceToken": visitor_id,
            },
        }))
        .send()
        .await?
        .json()
        .await
}
```

| 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.

## Good to know

- `reqwest::Client` has no overall timeout unless you set one, so use `.timeout()` on its builder. Keep one `Client` and clone it, since it holds a connection pool.
- 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 |
| --- | --- |
| Axum, Actix Web | Both run on Tokio, so these `async` functions fit in a handler as they are. Take the answers as a typed form, which also names your fields, and read `Origin` from the request's headers. |
| The retry sample | It also needs `rand`, and a `uuid` for its key. The spam check sample needs `chrono` and `uuid`. |
| No async runtime | `reqwest::blocking`, behind the `blocking` feature, takes the same calls with no `.await`. |

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