Stop form spam in FastAPI

Updated

This guide adds Bot403 to a contact form in FastAPI. The browser solves a small proof of work, and your route checks the token with one call before it accepts the message. The free plan covers 5,000 checks a month. The trap is FastAPI's async def: the bot403 package is synchronous, so the route that calls it must be a plain def.

The example uses FastAPI 0.162.5, python-multipart 0.0.33 and bot403 0.1.0 from PyPI. python-multipart needs Python 3.11 or newer, so the app does too.

On 12 November 2026, we ran this code and the three tests in "Test it" with FastAPI 0.162.5, Starlette 1.10.0, python-multipart 0.0.33, bot403 0.1.0 and Python 3.12, against a stand-in for the Bot403 client. All three tests passed.

Before you start

Sign in. Create a site. Copy its public key (pk_) and its secret key (sk_). Put the secret key in an environment variable, never in your code or your repository.

Terminal
uv add fastapi python-multipart uvicorn bot403   # or: pip install fastapi python-multipart uvicorn bot403
export BOT403_SECRET_KEY=sk_live_YOUR_SECRET_KEY

FastAPI needs python-multipart to read a form. Without it, the first form you send fails.

The app is one file, with its tests next to it:

Layout
main.py
test_main.py

1. The page with the form

The script tag protects every form on the page. Before the browser sends the form, the script adds a hidden _bot403 field with the token. It also adds a hidden honeypot field.

main.py
import logging
from functools import lru_cache
from typing import Annotated

from bot403 import Bot403, Bot403Error
from fastapi import Depends, FastAPI, HTTPException, Request
from fastapi.responses import HTMLResponse, RedirectResponse
from starlette.datastructures import FormData

log = logging.getLogger(__name__)
app = FastAPI()

PAGE = """<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Contact</title>
  <script src="https://bot403.com/v1/bot403.js" data-bot403-key="pk_live_YOUR_PUBLIC_KEY" async></script>
</head>
<body>
  <form method="post" action="/contact">
    <label>Email <input name="email" type="email" required></label>
    <label>Message <textarea name="message" required></textarea></label>
    <button type="submit">Send</button>
  </form>
</body>
</html>"""


@app.get("/contact", response_class=HTMLResponse)
def contact_page():
    return PAGE


@app.get("/thanks")
def thanks():
    return {"message": "Thanks. Your message is on its way."}

If you render pages with Jinja2, put the same script tag in the <head> of your template.

2. The client and the form, as dependencies

Two small dependencies give the route what it needs. get_bot403() makes one Bot403 client, the first time a form arrives. submitted_form() reads the whole form.

main.py
@lru_cache
def get_bot403() -> Bot403:
    # Reads BOT403_SECRET_KEY. Raises ValueError without it.
    return Bot403(timeout=5)


async def submitted_form(request: Request) -> FormData:
    return await request.form()

The client is not made at import time. Bot403() raises ValueError when BOT403_SECRET_KEY is not set. At import, that error would stop the app and every test, even tests that never send a form. As a dependency, the client is made once, on the first form, and a test can replace it.

3. The route

The route sends the whole form to Bot403. verify_form() posts it to https://bot403.com/api/v1/verify with your secret key. The route accepts the message only when the answer is ok. If Bot403 does not answer, the route accepts the form and logs a warning. A wrong secret key or too many verify calls a minute raise an error, so you see them and fix them.

main.py
def bot403_check(bot403: Bot403, form: FormData) -> bool:
    # 1. Post the whole form. Bot403 reads the _bot403 field and the honeypot field.
    try:
        result = bot403.verify_form(form)
    except Bot403Error as e:
        if e.status != 0:
            raise  # 401 wrong key, 429 too many calls: fix these, do not hide them
        log.warning("bot403 did not answer, letting the form through: %s", e)
        return True
    # 2. Refuse when ok is false, except for reason "quota"
    return result.ok or result.reason == "quota"


@app.post("/contact")
def contact(
    form: Annotated[FormData, Depends(submitted_form)],
    bot403: Annotated[Bot403, Depends(get_bot403)],
):
    if not bot403_check(bot403, form):
        raise HTTPException(status_code=400, detail="The form check failed. Please send it again.")
    # A real visitor: send the email or store the message here
    return RedirectResponse("/thanks", status_code=303)

A failed token is a normal answer, not an exception: result.ok is False and result.reason says why. The verify page lists every reason. The 303 status makes the browser load /thanks with a GET.

The trap: async def and a synchronous client

Keep the route a plain def. The bot403 package uses only the Python standard library, and its call waits for the answer from the verify API. FastAPI runs a plain def route in a threadpool, so this wait blocks only that one request. FastAPI's docs say a def route "is run in an external threadpool that is then awaited, instead of being called directly (as it would block the server)".

If you write async def contact and call verify_form() in it, the call runs on the event loop. Every other request on that worker then waits for the verify call, up to the 5-second timeout. Nothing fails in a test with one request, so you see this only under load.

The form dependency can stay async def. Reading the form is async in FastAPI, and FastAPI awaits the dependency before it runs the plain def route.

If the route must be async def, for example because it awaits an async database, run the check in the threadpool yourself:

main.py
from starlette.concurrency import run_in_threadpool

ok = await run_in_threadpool(bot403_check, bot403, form)

Forms sent with fetch or JSON

If you send the form with fetch, send it as FormData. Then the honeypot field goes with it, and the route above works as it is. The script listens to the submit event before your own code does. It waits for the token, puts it in the _bot403 field, and then submits again. So when your handler runs, the form already holds the token:

contact.js
const form = document.querySelector("form");
form.addEventListener("submit", async (event) => {
  event.preventDefault();
  // holds _bot403 and the honeypot field
  const res = await fetch(form.action, { method: "POST", body: new FormData(form) });
  if (res.ok) location.href = res.url;
});

If your front end sends JSON, put the token in the body and check it with bot403.verify(token). This sends the token alone, so Bot403 cannot check the honeypot field. Use FormData when you can.

main.py
from pydantic import BaseModel, Field


class Message(BaseModel):
    email: str
    message: str
    token: str = Field(alias="_bot403")


@app.post("/api/contact")
def api_contact(body: Message, bot403: Annotated[Bot403, Depends(get_bot403)]):
    try:
        result = bot403.verify(body.token)
    except Bot403Error as e:
        if e.status != 0:
            raise
        result = None  # Bot403 did not answer: let the message through
    if result and not result.ok and result.reason != "quota":
        raise HTTPException(status_code=400, detail="The form check failed.")
    return {"ok": True}

CSRF is yours to add

FastAPI has no CSRF check built in, unlike Django or Flask-WTF. Bot403 does not do that job. It stops scripts that send forms automatically. CSRF protection stops other sites that send forms in the name of your visitor. If your form acts for a signed-in visitor, add a CSRF check too. A public contact form with no session usually needs none.

Test it

The tests replace the Bot403 client with a fake that gives a fixed answer. app.dependency_overrides does this, so the tests need no network and no key. FastAPI's test client needs an HTTP client package. Starlette 1.10 asks for httpx2, and warns that httpx is deprecated for its test client.

test_main.py
from bot403 import Bot403Error, Result
from fastapi.testclient import TestClient

from main import app, get_bot403


class FakeBot403:
    """Stands in for the Bot403 client: no network, no key."""

    def __init__(self, answer):
        self.answer, self.sent = answer, None

    def verify_form(self, form):
        self.sent = dict(form)
        if isinstance(self.answer, Exception):
            raise self.answer
        return self.answer


def client(answer):
    fake = FakeBot403(answer)
    app.dependency_overrides[get_bot403] = lambda: fake
    return TestClient(app), fake


def teardown_function():
    app.dependency_overrides.clear()


def test_verified_form_goes_through():
    c, fake = client(Result(ok=True))
    r = c.post("/contact", data={"email": "[email protected]", "_bot403": "token"}, follow_redirects=False)
    assert r.status_code == 303 and r.headers["location"] == "/thanks"
    assert fake.sent["_bot403"] == "token"


def test_failed_token_is_refused():
    c, _ = client(Result(ok=False, reason="invalid"))
    assert c.post("/contact", data={"email": "[email protected]"}).status_code == 400


def test_bot403_down_lets_the_form_through():
    c, _ = client(Bot403Error("network", 0, "network"))
    r = c.post("/contact", data={"email": "[email protected]"}, follow_redirects=False)
    assert r.status_code == 303
Terminal
uv add --dev pytest httpx2   # or: pip install pytest httpx2
python -m pytest -q

Then run uvicorn main:app --reload. Open http://127.0.0.1:8000/contact. Send the form. The browser goes to /thanks, and the site in your dashboard shows one check.

Troubleshooting

  • Every form gets a 400. Log result.reason in bot403_check. If it is invalid, the form arrives without a _bot403 field. Check that the script tag is on the page and that the public key is right. In the browser's developer tools, the form data of the POST must hold _bot403.
  • An error about python-multipart when a form arrives. Install python-multipart. FastAPI needs it to read forms.
  • ValueError: bot403: pass the site's secret key. BOT403_SECRET_KEY is not set in the environment of the server, or it holds the public key.
  • Your own end-to-end tests with Playwright get automation. That is on purpose. Use a separate test site with Automated browsers set to Off.

The troubleshooting page lists every reason and its fix. For other Python frameworks, read Stop form spam in Flask and Stop form spam in Django. All guides are on the guides page.

Stop spam, not customers.

The CAPTCHA your visitors never see.

Get started free