TrustComponent
FastAPI
TrustCaptcha · Bot protection

FastAPI CAPTCHA Integration

Set up a FastAPI CAPTCHA in a path operation with a few lines of Python. TrustCaptcha stops bot spam on logins, signups and contact forms through a Depends() dependency that fits FastAPI's async, typed style. EU-hosted, GDPR-compliant, no image puzzles.

Quickstart

How the integration works

1. Create a CAPTCHA

Create a user account or log in with an existing one. Then create a new CAPTCHA or pick an existing one. If you want to try TrustCaptcha first, every plan comes with a 14-day free trial.

The CAPTCHA overview page shows your site key and license key, and you create your API key there. Add your website’s domains to the authorized domains in the CAPTCHA security rules so they can use your CAPTCHA.

Start of the CAPTCHA creation form.
CAPTCHA security rules of a demo CAPTCHA.

2. Add the CAPTCHA widget to your form

Drop the TrustCaptcha widget into the HTML form your FastAPI endpoint serves. The widget runs the CAPTCHA in the background and adds a hidden tc-verification-token field on submit, which FastAPI exposes via Form(..., alias="tc-verification-token").

contact.html
HTML
<script type="module" src="https://cdn.trustcomponent.com/trustcaptcha/3.0.x/trustcaptcha.esm.min.js"></script>

<form method="post" action="/contact">
    <input type="email" name="email" required>
    <trustcaptcha-component sitekey="<your_site_key>"></trustcaptcha-component>
    <button type="submit">Send</button>
</form>

The CAPTCHA widget will then be displayed inside your form:

CAPTCHA start

Need detailed information about the CAPTCHA widget integration?
Our documentation has the full widget reference, including themes, languages and custom design.

Read the documentation

3. Validate the token in your FastAPI endpoint

In your FastAPI path operation, take the verification token from the form, look up the result via our Python library, and decide whether to accept the request.

First, install our TrustCaptcha Python library:

Install
bash
pip install "trustcaptcha>=3.0.0,<4.0.0"

Then validate the token inside your FastAPI endpoint and act on the result:

main.py
Python
from fastapi import FastAPI, Form, HTTPException
from fastapi.concurrency import run_in_threadpool
from trustcaptcha.trust_captcha import TrustCaptcha

app = FastAPI()

@app.post("/contact")
async def submit(
    email: str = Form(...),
    tc_verification_token: str = Form(..., alias="tc-verification-token"),
):
    trust_captcha = TrustCaptcha("<your_api_key>")
    try:
        result = await run_in_threadpool(trust_captcha.get_verification_result, tc_verification_token)
    except Exception:
        raise HTTPException(status_code=400, detail="CAPTCHA verification failed.")

    if not result.verification_passed or result.score > 0.5:
        raise HTTPException(status_code=400, detail="CAPTCHA verification failed.")

    # CAPTCHA passed — process the request
    return {"status": "ok"}

Need detailed information about the FastAPI CAPTCHA integration?
For full step-by-step instructions, including a reusable Depends() dependency for projects with several protected endpoints, please read our documentation.

Read the documentation

Other backend framework instead of FastAPI?
If you use a different framework, pick the matching recipe here. If your framework isn’t listed, your software developers can integrate the verification themselves using our documentation or ask our support team for a pre-built integration.

Actix Web
ASP.NET Core
Axum
Django
Echo
Express
FastAPI
Fastify
Fiber
Flask
Gin
Hapi
Laravel
Micronaut
NestJS
Next.js
Quarkus
Ruby on Rails
Sinatra
Spring Boot
Symfony

4. Test your integration

TrustCaptcha is now active. Send a test request and check that it goes through.

CAPTCHA done

FAQs

Where does the FastAPI CAPTCHA check go?
Inside the path operation that handles the form submission, or, for several protected endpoints, inside a custom Depends() dependency. Both work the same way: pull the token from a Form(...) parameter, run the verification, raise HTTPException on failure.
How do I read the CAPTCHA token from a form post?
Declare it as a form parameter with Form(...) and an alias for the dashed name: tc_verification_token: str = Form(..., alias="tc-verification-token"). FastAPI then maps the widget's hidden tc-verification-token field onto your Python parameter.
Can I share a single TrustCaptcha instance across endpoints?
Yes. Use FastAPI's dependency injection: declare a get_trust_captcha() function decorated with @lru_cache that returns a single TrustCaptcha instance. Inject it via Depends(get_trust_captcha) in your endpoints or in a verify_trust_captcha dependency.
Why wrap the verification call in run_in_threadpool?
Because the Python SDK is synchronous (blocking I/O). Inside an async def endpoint, calling it directly would block the event loop. run_in_threadpool(...) (or asyncio.to_thread) hands it off to a worker thread so other requests keep flowing. In a sync def endpoint, FastAPI does this for you automatically.
How do I use TrustCaptcha with a JSON request body instead of a form post?
Declare the token in your Pydantic request model and read it from the model inside the endpoint or dependency. The verification call itself stays the same, however the token reached your backend.
Losing leads to CAPTCHAs?

TrustCaptcha blocks spam and bots, not customers. No puzzles, GDPR-compliant, EU-hosted.

CAPTCHA start
CAPTCHA done
No puzzles for visitors
The check runs in the background while visitors type, so more people finish your forms instead of giving up.
GDPR-compliant
Hosted in the EU, no cookies, encrypted transmission and automatic data deletion. Every customer gets a Data Processing Agreement.
Multi-layer security
Adaptive proof-of-work and risk scoring stop abuse early, even when attack traffic spikes.
Full control
Set the sensitivity, keep allow and block lists and use geoblocking. You decide how strict the check is.

Protect your FastAPI application with TrustCaptcha in just a few steps!

  • EU-hosted & GDPR-compliant
  • No puzzles
  • Try free for 14 days