Add e-signatures and clickwrap to FastAPI
To add e-signatures and clickwrap to FastAPI, call the REST API from your path operations with one shared httpx.AsyncClient. There is no Python package: the server SDK exists for Node.js only. One operation creates the session with the secret key, another confirms the record, and the browser SDK attaches to your own form. Esign Comply seals each acceptance.
Follow the quickstart and each signature is a valid electronic signature under the U.S. ESIGN Act, state UETA laws and New York's ESRA, and each clickwrap is built the way courts require: clear notice of the terms, an unmistakable act of assent, and a sealed record of both.
$pip install fastapi "uvicorn[standard]" httpxFree plan: 10 live signatures a month and a full test mode. No card required.
Last updated
@asynccontextmanager async def lifespan(app: FastAPI): # There is no Python package: one async HTTP client carries the secret key for the whole app. async with httpx.AsyncClient( base_url=os.environ.get("ESIGNCOMPLY_API_URL", "https://esigncomply.com/v1"), headers={"Authorization": f"Bearer {os.environ['ESIGNCOMPLY_API_KEY']}"}, timeout=10, ) as client: app.state.esc = client yield async def call(request: Request, method: str, path: str, **kwargs) -> httpx.Response: """One call to the Esign Comply API through the shared client.""" for attempt in range(3): response = await request.app.state.esc.request(method, path, **kwargs) # Over the rate limit: wait for Retry-After (5 seconds at most) and try again, twice at most. Nothing else is retried. if response.status_code != 429 or attempt == 2: break await asyncio.sleep(min(float(response.headers.get("Retry-After") or 1), 5)) # awaited: no other request waits return response app = FastAPI(lifespan=lifespan)
# Step 4: create the session with the secret key. The browser gets the client token only. @app.post("/api/ceremony") async def ceremony(request: Request): origin = request.headers.get("origin") or str(request.base_url).rstrip("/") response = await call( request, "POST", "/sessions", headers={"Idempotency-Key": f"signup-{SIGNER['external_id']}-{uuid.uuid4()}"}, json={ "profile": os.environ["ESIGNCOMPLY_PROFILE_ID"], "signer": SIGNER, "documents": [ {"document": DOCUMENTS["terms"], "version": "current"}, {"document": DOCUMENTS["privacy"], "version": "current"}, ], "context": {"url": f"{origin}/signup", "locale": "en-US", "purpose": "account_signup"}, }, ) if response.status_code != 201: raise HTTPException(502, response.json().get("error", {}).get("code")) session = response.json() pinned[SIGNER["external_id"]] = sorted(d["version_id"] for d in session["documents"]) return {"clientToken": session["client_token"], "apiUrl": session["api_url"], "documents": session["documents"]}
class Confirmation(BaseModel): recordId: str # from the browser: a claim to check # Step 6: confirm the record with the secret key before the account exists. @app.post("/api/signup/confirm") async def confirm(body: Confirmation, request: Request): response = await call(request, "GET", f"/records/{quote(body.recordId, safe='')}") record = response.json() confirmed = ( response.status_code == 200 and record["status"] in SEALED and record["livemode"] is LIVE and record["signer"]["external_id"] == SIGNER["external_id"] and sorted(d["version_id"] for d in record["documents"]) == pinned.get(SIGNER["external_id"]) ) print(f"confirmed {record['id']} ({record['status']})" if confirmed else "refused", flush=True) if not confirmed: raise HTTPException(409, "not_confirmed") # Only now create the account, and store record["id"] and record["receipt"] with it. return {"confirmed": True, "recordId": record["id"]}
How do you integrate Esign Comply with FastAPI?
FastAPI path operations are async def, so the client is async too. The lifespan function opens one httpx.AsyncClient that carries the secret key, every operation awaits it, and a Pydantic model checks the confirm body before any call is made. uvicorn loads the key with --env-file.
FastAPI is a modern, fast (high-performance), web framework for building APIs with Python based on standard Python type hints.
Source: FastAPI documentation, read on .- The clientmain.py
- Create the sessionmain.py
- Confirmmain.py
Run on 2026-11-26 with FastAPI 0.128.8, uvicorn 0.39.0, httpx 0.28.1 and pydantic 2.13.5 on Python 3.9.25, with the browser SDK script build and the conformance check from esigncomply 1.0.4, against the API in test mode.
What prompt adds Esign Comply clickwrap to a FastAPI app?
Paste this into Cursor, Claude Code or the AI coding tool that is open on your project. It names the packages that exist, where the secret key goes in FastAPI, what to build and what never to do, and it ends with the rules block for your project.
The rules block lives at /rules.md. Added to your project's instruction file, it makes every later session build signing and acceptance flows the same way. The prompt generator writes the long version, with your own document and profile IDs.
Pages for each AI toolAdd Esign Comply clickwrap to my FastAPI app: a signup form where the user accepts the Terms of Service and the Privacy Notice with a checkbox and a button.
Read these first and follow them exactly. If something conflicts with existing code, or you are unsure how to implement a step, stop and ask. Do not invent API methods, packages or legal wording.
- https://esigncomply.com/docs/quickstart/fastapi.md (the steps and the tested code for FastAPI)
- https://esigncomply.com/setup.md (the order of API calls)
- https://esigncomply.com/auth.md (how to handle the keys)
FastAPI facts
- There is no Esign Comply package for Python. Do not install or invent one. The server calls the REST API at https://esigncomply.com/v1 with Authorization: Bearer and the secret key.
- Use one httpx.AsyncClient for the app, created in the lifespan function. Never call a blocking HTTP client inside an async def path operation: it stalls every other request.
- The browser SDK is a script tag: https://esigncomply.com/sdk/v1/esigncomply.js. It defines the global EsignComply.
- The secret key is in the environment variable ESIGNCOMPLY_API_KEY. Load .env with: uvicorn main:app --env-file .env. Never print the key.
- Each uvicorn worker is its own process. Keep the pinned version IDs in the database, not in a module-level dict.
- The page is on screen before the script has a session: render the checkbox disabled and enable it when observeAssent has resolved.
Build
1. Verify the key: GET /v1/usage with ESIGNCOMPLY_API_KEY. Stop if it fails.
2. Register the Terms of Service and the Privacy Notice as documents and publish one version of each from the documents in this project. If the project has none, register short sample documents and say so in your report. Never write or change the wording of the real documents. Create a profile: jurisdictions ["US-FED"], method "checkbox", assurance_level "L1".
3. Server: POST /api/ceremony calls POST /v1/sessions with an Idempotency-Key, saves the signer ID and the pinned version IDs in server-owned state, and returns only clientToken, apiUrl and documents.
4. Server: GET /legal/{slug} renders the html from GET /v1/documents/{id}/versions/{version_id}/content inside <article data-esc-document>, unmodified.
5. Browser: EsignComply.attach({ clientToken, apiUrl }), presentDocument for each link, observeAssent({ region, checkbox, submit }), then complete() from the user's real click.
6. Server: POST /api/signup/confirm takes a Pydantic model with recordId, calls GET /v1/records/{id} and requires: status is "recorded", "timestamped" or "anchored"; livemode is as expected; the signer ID and version IDs equal the server-owned state. Only then create the account.
Never
- Never pre-check the box, auto-submit, or call .click() on the user's behalf.
- Never use "By continuing" or "By clicking below" wording. The notice names the button by its label and each document by its registered name.
- Never put the secret key, or any call that uses it, in code that reaches the browser.
- Never show "signed" or "accepted" before the server has confirmed the record.
- Never fall back to an acceptance with no record when a session is refused.
Check before you report success
- Run: npx esigncomply check --url http://localhost:8000/signup --callback http://localhost:8000/api/signup/confirm
Fix every finding marked "block". List every finding marked "warn".
- Report the files you created or changed, anything you did not implement and why, and the conformance summary.
Then add the rules block to this project's instruction file: https://esigncomply.com/rules.mdWhat goes wrong when you add e-signatures in FastAPI?
These are specific to FastAPI. Each one was seen while the quickstart's code was run, or is in FastAPI's own documentation.
- 01
A blocking client inside async def stalls every request
In a test with FastAPI 0.128.8, a request to another route waited 1.71 seconds behind a 2 second blocking call inside an
async defoperation, and took 0.001 seconds on its own. Usehttpx.AsyncClientand await it. - 02
Each uvicorn worker has its own memory
The quickstart keeps the pinned version IDs in a module-level dict. With
--workers 2, a request that reached the second worker did not see what the first had stored. Put that state in your database before you add workers. - 03
uvicorn loads .env, FastAPI does not
uvicorn main:app --env-file .envputs the variables into the environment before it imports your app. The flag needspython-dotenv, whichuvicorn[standard]installs. Without it,os.environraisesKeyErrorwhen the module loads.
Where are the FastAPI quickstart and the API reference?
Start with the quickstart: it carries every file this page excerpts, in the order you write them.
- QuickstartFastAPI quickstartStep by step, from install to your first sealed test record, with every file and the output of each step.Open
- ReferenceAPI referenceEvery endpoint, field and error code. Sessions, records and documents are the three this page uses.Open
- GuideServer confirmationThe one place access is granted: what to compare, and the webhook that backs the check up.Open
What does Esign Comply record for a signature in FastAPI?
The same record on every stack and platform. Your FastAPI code creates the session and confirms the record, and the browser SDK reports what happened on the page. Esign Comply seals the result where your code cannot change it. The record itself is described on Evidence and verification.
Observed and asserted fields
Every field is tagged. Observed is what the browser SDK and the API saw: the box unchecked at load, the tick from a trusted user event, the notice text, the terms version by hash, the server time. Asserted is what your app said, such as the user's email.
A signed receipt
complete()returns a receipt signed with ES256, using keys you do not hold. Your server stores it next to the user, andGET /v1returns it again./records /{id} /receipt An external timestamp
An outside authority timestamps the hash of every live record (RFC 3161), so the time on the record does not rest on your clock or on ours.
An offline verifier
Each record has an evidence report (PDF) and an evidence package (ZIP). Anyone you send the package to checks the acceptance with the open-source
esigncomply-verify, without an account.
Questions about e-signatures in FastAPI
Is there an Esign Comply SDK for FastAPI?
No. The server SDK exists for Node.js only. FastAPI calls the REST API directly, and the quickstart does it with one httpx.AsyncClient shared by every path operation. The browser side is the same SDK as on every stack.
Where do I create the session in FastAPI?
In a path operation, for example @app.post("/api, that awaits a POST to /v1 with the secret key and an Idempotency-Key. It returns only the client token, the API URL and the pinned documents.
Why one AsyncClient in lifespan?
So every request reuses the same connection pool and the secret key is set in one place. The lifespan function opens the client when the app starts and closes it when the app stops.
What does the Pydantic model add to the confirm route?
It refuses a malformed body before any API call. In the test run, a body without recordId was answered 422 by the model, and a made-up record ID was answered 409 after the API returned not_found.
Can I use sync def path operations instead?
Yes, with a blocking client. FastAPI runs a def operation in a thread pool, so it does not hold the event loop. What you must not do is call a blocking client inside async def.
Add two path operations to your FastAPI app. Leave the record to us.
Free plan: 10 live signatures a month and a full test mode. No card required.
FastAPI is a trademark of its owner. Esign Comply is not affiliated with it. What this page says about FastAPI is from FastAPI's documentation or from a test run, as marked, on . /fastapi.md is this page as Markdown.