Fingerly for Python
Read events, verify webhooks and serve a first-party proxy from your Python backend, with sync and asyncio clients.
fingerly is the server-side Python package for Fingerly, which identifies the device behind every web and app session and scores how suspicious it is. Use it to protect signups, logins and payments: read the event the browser SDK produced with a server-only secret key, verify webhook signatures, and relay the browser SDK's traffic through your own domain.
Two clients share one API: Fingerly for synchronous code such as Django and Flask, and AsyncFingerly for asyncio code such as FastAPI and Starlette. Python 3.9 or newer. One runtime dependency, httpx. The proxy serves both ASGI and WSGI, so it mounts under either.
1. Prerequisites. A Fingerly account and a secret key (see API keys and environments). A webhook signing secret to verify webhooks, and a proxy key (see Proxy integrations) for the proxy.
2. Install.
pip install "fingerly>=0.4.1"3. Read an event.
import os
from fingerly import Fingerly
fingerly = Fingerly(secret_key=os.environ["FINGERLY_SECRET_KEY"])
page = fingerly.events.list(level="high", limit=50)
event = fingerly.events.get(page.rows[0].request_id)The same with AsyncFingerly:
import asyncio
import os
from fingerly import AsyncFingerly
async def main() -> None:
async with AsyncFingerly(secret_key=os.environ["FINGERLY_SECRET_KEY"]) as fingerly:
page = await fingerly.events.list(level="high", limit=50)
for row in page.rows:
print(row.request_id, row.suspect_score)
asyncio.run(main())4. Verify a webhook.
import os
from flask import Flask, abort, request
from fingerly import WebhookEventType, verify_webhook
app = Flask(__name__)
@app.post("/webhooks/fingerly")
def fingerly_webhook():
if not verify_webhook(
secret=os.environ["FINGERLY_WEBHOOK_SECRET"],
payload=request.get_data(),
timestamp=request.headers.get("x-fingerly-timestamp"),
signature=request.headers.get("x-fingerly-signature"),
):
abort(400)
delivery = request.get_json()
if delivery["type"] == WebhookEventType.VISITOR_SUSPECT:
print(delivery["data"])
return "", 204In a web app, build the client once and reuse it: see Framework guides for FastAPI, Django and Flask.
Full documentation: docs.fingerly.io/docs/sdks/python.
| I want to | Go to |
|---|---|
| Read an event | Read events |
| Verify and consume an event before a backend action | Verify a backend action |
| Read or write an iOS device's DeviceCheck bits | Read and write Apple DeviceCheck bits |
| Check a webhook signature | Verify webhooks |
| Keep identification working behind content blockers | First-party proxy |
| Mount the proxy in FastAPI, Django or Flask | Framework guides |
| Tune deadlines, pools and the API version | Timeouts, Connections, API version |
- Read events
- Read and write Apple DeviceCheck bits
- Verify webhooks
- First-party proxy
- Framework guides
- Timeouts
- Connections
- API version
- Development and release preparation
- Requirements
- Documentation
- Help
- Licence
Event reads require fly_sk_{production|staging|development}_… keys. Requests go to https://api.fingerly.io; endpoint overrides that for a local API. endpoint takes a scheme, a host and an optional port and nothing else: a path, query, fragment, credentials, space or control character is refused when the client is built. It must be https. Plain http is accepted only for 127.0.0.1, localhost or [::1], and only with allow_insecure_loopback=True, which is meant for local development and tests. Public, proxy, management, malformed and unsupported keys are rejected before network access. Requests do not follow redirects. get and list each perform one request and never retry.
Fingerly |
AsyncFingerly |
|
|---|---|---|
| Calls | fingerly.events.get(id) |
await fingerly.events.get(id) |
| Closing | fingerly.close() or with Fingerly(...) as fingerly: |
await fingerly.aclose() or async with AsyncFingerly(...) as fingerly: |
Each client holds pooled connections. Build one and reuse it; build one per event loop for AsyncFingerly.
Never call
Fingerlyfromasync defcode. It blocks the event loop for the whole request, so every other request on that worker waits behind it: five reads against a slow API stall a FastAPI worker for five timeouts in a row. UseAsyncFingerlythere, or a plaindefroute, which FastAPI and Starlette run in a thread.Fingerlyraises aRuntimeWarning, once per process, when it finds itself on a running event loop.
Send the requestId the browser SDK returned to your server and read it there with fingerly.events.get(request_id), or await fingerly.events.get(request_id) with AsyncFingerly. A 404 carries one of two codes:
| Code | Raises | Meaning |
|---|---|---|
event_pending |
FingerlyEventPendingError, a FingerlyAPIError |
The request id was accepted but its event is not recorded yet. It is not a verdict. Try again after retry_after seconds, or verify asynchronously, for example from a webhook. The SDK never retries on its own. |
event_not_found |
a plain FingerlyAPIError |
The request id was never issued for this key's environment, or the event is past the 30-day retention. |
The archived document arrives moments after the event itself, so check has_document rather than assuming it is there, and call event.parse_document() when you want a typed EventDocument.
ip_networkis the network the request came from (an IPv4 /24 or an IPv6 /40, such as203.0.113.0/24); the API never returns the address.- When a submission is unidentifiable (
event.identifiable is False, such as insufficient entropy, a genuine embedded WebView, or an unmatched high-risk Web payload),event.visitor_idis"". There are nodeferred_token,deferred_signalsorsupplementsfields inv: 3. document, when available, is an allow-listed view of the archived request with no raw signals, user agent or address.event.parse_document()decodes it into a typedEventDocument(includingattestation: Optional[Attestation]). A nativeAttestationalso carriesattest_skipped(the app's reason for sending no proof) anddowngrade(the report named an install an attested device owns).suspect_level,state,environment, each trigger'ssignalandconfidence, and anAttestation'sstate,statusandattest_skippedhold the string the API sent. Compare them with the matching enum:SuspectLevel,EventState,Environment,Signal,Confidence,AttestationState,AttestationStatusandAttestSkippedReason. Every member is astrequal to its value, soevent.suspect_level == SuspectLevel.HIGHandSignal.FINGERPRINT_SUPPRESSED in signalswork on plain strings, and a value a newer server adds still parses. Compare rather than convert:SuspectLevel(value)raisesValueErrorfor a value this release does not know.Signalnames every signal group and detector, including thev: 3anti-spoofing and integrity signalsATTESTATION_FAILED,ATTESTATION_DOWNGRADE,DEVICE_INCONSISTENT,REPORT_INCOMPLETE,PROBE_ERRORS,FETCH_METADATA_MISSING,WEB_TICKET_MISSING,WEB_TICKET_INVALID,TAMPERING,CUSTOM_ROOT_CAandSECONDARY_USER_PROFILE.SIGNAL_NAMESholds the same values as plain strings.
from fingerly import Signal, SuspectLevel
signals = [trigger.signal for trigger in event.triggers]
if event.suspect_level == SuspectLevel.HIGH or Signal.FINGERPRINT_SUPPRESSED in signals:
send_to_review(event)suspect_scoreisNonewhen the request was not scored, and must not be treated as zero.project_idis the UUID string of the Fingerly project the event belongs to, on bothevents.getand the rows ofevents.list; it isNonewhen an older server does not send it.Eventdeclares every documented field as an attribute and falls back to the decoded body for fields added later, so a new server field needs no SDK upgrade.
FingerlyAPIError provides status, and optional code, details, request_id and retry_after, the seconds a 429, a 503 or a 404 event_pending asks you to wait (None when the response did not say). The secret key is stripped from all of them. Every status outside 2xx raises it, a redirect included, since requests never follow one. FingerlyTimeoutError and FingerlyConnectionError cover a deadline and an unreachable API; all three derive from FingerlyError.
Send the browser's requestId to your server and verify it there with a server-only key. fingerly.events.verify reads the event and runs these checks in order, stopping at the first that fails:
| Order | Reason | VerifyReason |
Fails when |
|---|---|---|---|
| 1 | not_found |
NOT_FOUND |
The event does not exist for this key's environment. |
| 2 | too_old |
TOO_OLD |
It occurred more than max_age_seconds ago (300 by default). A missing or unreadable occurred_at fails too. |
| 3 | tag_mismatch |
TAG_MISMATCH |
You passed tag and the event's tag is not exactly that. |
| 4 | unidentifiable |
UNIDENTIFIABLE |
The event has no visitor id. |
| 5 | unscored |
UNSCORED |
The event has no suspect_score. |
| 6 | already_consumed |
ALREADY_CONSUMED |
The event was consumed before. |
Consumption comes last, only when every other check passed, so one event backs one decision: a replayed requestId answers already_consumed. Pass consume=False to check without consuming. The result is a VerifyResult with ok, reason (a VerifyReason, VerifyReason.OK or "" when ok, and equal to the strings above otherwise) and event (None only for not_found).
verify never judges the score: that policy stays with you. Check suspect_level or suspect_score after ok.
from fingerly import SuspectLevel, VerifyReason
result = fingerly.events.verify(request_id, tag="checkout")
if result.reason == VerifyReason.ALREADY_CONSUMED:
refuse_replay()
elif not result.ok:
refuse(result.reason)
elif result.event.suspect_level == SuspectLevel.HIGH:
send_to_review(result.event)
else:
allow()AsyncFingerly has the same call as a coroutine. An invalid option (a max_age_seconds that is not a positive integer, an empty tag) raises TypeError before anything is sent. fingerly.events.consume(request_id) consumes an event on its own: the first call answers a ConsumeResult with first=True, and every later one raises FingerlyEventAlreadyConsumedError, a FingerlyAPIError whose consumed_at says when. Neither call is retried.
Do not authorize an action using scores or visitor identifiers supplied by the browser. Tags correlate events; they do not replace your application's authentication. A tag must never hold a personal identifier, such as a user ID, email, install ID or advertising ID, because the server keeps tags in long-lived rollups. verify raises every error other than event_not_found and event_already_consumed. A FingerlyEventPendingError means the server has not decided yet: retry after retry_after seconds or verify asynchronously, and do not refuse the action as fraud on that answer alone. The framework guides below answer it with 503 and Retry-After.
For an iOS identification whose App Attest evidence carried a DeviceCheck token, Fingerly holds the token for one hour, and a secret key of the same project and environment can spend it once: to read the device's two bits from Apple, or to set them. The bits mean what you decide; Fingerly never stores or reads them.
Apple treats a DeviceCheck token as single-use, so a read and a write each need their own identification. A once-per-device free trial takes two:
- Query on the identification that asks for the trial. If the bit says the device already had one, refuse it.
- Otherwise grant the trial and record the grant in your own data.
- Write the bit on the next identification from that install. Until the write lands, your own record of the grant is what stops a second trial.
from fingerly import FingerlyDeviceCheckError
# The identification that asks for the trial.
try:
bits = fingerly.device_check.query(request_id)
used_on_device = bits.found and bits.bit0
except FingerlyDeviceCheckError as error:
if error.code not in ("device_check_not_held", "device_check_spent"):
raise
used_on_device = False # no answer, not a verdict
# The next identification, after you recorded the grant.
fingerly.device_check.write(next_request_id, bit0=True)AsyncFingerly has the same calls as coroutines. write sends only the bits you name; naming neither raises TypeError before anything is sent.
Every non-2xx answer raises FingerlyDeviceCheckError (a FingerlyAPIError); branch on code:
| Status | code |
|---|---|
404 |
device_check_not_held |
409 |
device_check_spent, device_check_busy or credential_unavailable |
422 |
bits_required or apple_rejected (with Apple's HTTP status in apple_status) |
503 |
device_check_unavailable |
A 503 or a transport failure leaves the token held, and the SDK retries the identical request, at most twice. A held token kept for a retry accepts only the request it was first used for: a retry with the other operation or other bits answers 409 device_check_spent. No other answer is retried.
The example under Getting started verifies a delivery in Flask.
identification.completed and visitor.suspect deliveries carry the event's project as data["project_id"]; identification.refused carries it only when the refused request named a known key. The SDK passes the payload through unmodelled, so read it from the parsed JSON. Compare its type with WebhookEventType (IDENTIFICATION_COMPLETED, IDENTIFICATION_REFUSED, VISITOR_SUSPECT, BILLING_STATUS_CHANGED, USAGE_DAILY_SETTLED, and WEBHOOK_TEST from Send test event), and ignore types you do not handle.
Verify the exact raw bytes before JSON parsing. Signatures cover the timestamp and body. The default replay tolerance is 300 seconds; persist processed webhook IDs to deduplicate deliveries. During signing-secret rotation, any matching signature in the comma-separated header is accepted; only the first 32 are read. The function never raises for malformed input: bad input is a failed verification, not an exception.
Content blockers refuse browser requests to third-party APIs, and a refused identification is a visitor never identified. Mount the proxy on a path of your own site and those requests become first-party. The proxy key is what lets that hop declare the visitor's real address, origin and user agent; a public key alone never can, so nobody can spoof them.
Create a proxy in the dashboard (Integration > Proxy keys). It issues the proxy key and a random path, such as /k7x2qm4a, for you to serve it on. One FingerlyProxy holds the configuration and exposes both server standards, so a project running each gets the same behaviour from one instance.
import os
from fingerly import FingerlyProxy
proxy = FingerlyProxy(
proxy_key=os.environ["FINGERLY_PROXY_KEY"],
path="/k7x2qm4a",
client_ip=lambda request: (
request.headers.get("cf-connecting-ip") or request.peer_host
),
)Then point the browser SDK at the same path:
const fingerly = await load({ apiKey: 'fly_pk_…', endpoints: '/k7x2qm4a' })| Your framework | Serve | Notes |
|---|---|---|
| FastAPI, Starlette, Django's ASGI stack, Quart, Litestar | proxy.asgi |
Under Starlette and FastAPI use app.add_route, not a Mount: Starlette answers a mount's bare path with a redirect to its slashed form, the browser SDK posts to the bare one, and the proxy does not answer the slashed one. |
| Flask, Django's WSGI stack, Pyramid | proxy.wsgi |
The framework guides show each in full.
path is the path the dashboard issued, within your application. With it set, the proxy answers that one path, exactly, and anything else gets 404, including anything under it, a trailing slash, another letter case, a dot segment or a percent-encoded spelling of the same path. It excludes anything a sub-URI deployment adds, and a path the mount has already stripped works too, so the same configuration serves an app at the root and one served from /shop. It is optional: leave it out and the proxy answers whatever your framework routes to it, which is safe only where the framework routes that one path and nothing else. There is no default path. Use the one the dashboard issued rather than inventing one: blockers look for words such as fingerprint, tracking and fingerly.
Browser and proxied native client SDKs post a single v: 3 identification envelope to that one path. The proxy forwards its raw request body bytes verbatim (without JSON decoding or re-serialising) to Fingerly's one ingest URL, https://api.fingerly.io/api/v1/ingest, and to nothing else. Event reads need a secret key and stay unreachable from a browser by construction.
| Situation | Answer |
|---|---|
Path other than the configured one (/supplement subpaths included) |
404 |
Method other than POST (plus OPTIONS when allowed_origins is configured), matched exactly, so post gets 405 too |
405 |
| No public key from the same environment as the proxy key | 401, nothing forwarded |
Neither Origin nor a validated x-fingerly-sdk-platform |
400 (missing_origin) |
| Body over 1 MiB (enforced while streaming rather than after buffering) | 413 |
| WSGI body the server cannot read, such as broken chunked framing | 400 |
| Fingerly cannot be reached in time | 504 Gateway timeout |
| Any other upstream failure: a refused connection, a malformed or truncated response, one over 4 MiB, an upstream redirect or a status outside 200 to 599 | 502 Bad gateway |
client_ip callback returns no valid address |
500 with the one line The client IP callback returned no valid address |
Responses are marked no-store. A redirect is never followed, whatever transport you supply. The 504 and 502 answers are short plain text marked no-store, and each writes one line, with no stack trace, to the fingerly.proxy logger. The line names the kind of failure only, never the upstream address or a key.
proxy_key is required, and a missing or malformed one fails when the proxy is built. The caller must present a public key (fly_pk_…) from the same environment as the proxy key, or the request gets 401 and nothing is forwarded. Upstream, the proxy sends that public key as X-API-Key and its own proxy key as X-Fingerly-Proxy-Key; a secret key is never part of the proxy.
Incoming headers follow the sanitize-and-restore sequence: all incoming x-fingerly-*, cookie and authorization headers are stripped, restoring x-fingerly-sdk-platform only when it matches an exact lowercase native or bridge platform (ios, android, react-native, react-native-ios, react-native-android, flutter, flutter-ios, flutter-android, lynx-ios, lynx-android, capacitor, kotlin-multiplatform). Requests carrying neither Origin nor a validated x-fingerly-sdk-platform are rejected locally with 400 (missing_origin), and x-fingerly-origin is never synthesized from Host, Referer or the request URL. Exactly one channel goes upstream: a request with an Origin is forwarded as a browser call with x-fingerly-origin and without the platform header, as the API treats the same request sent to it directly.
Alongside verified proxy metadata (x-fingerly-host included), only content-type, x-api-key, user-agent, idempotency-key, sec-fetch-* and sec-ch-ua-* are forwarded. Customer cookies and authorization headers are never passed on. The proxy reports itself upstream as python/0.4.1 in x-fingerly-proxy-version, which the dashboard shows per proxy, and sends fingerly-python/0.4.1 as its user agent.
Back to the browser it relays only content-type, x-request-id, ratelimit-limit, ratelimit-remaining and retry-after, plus its own cache-control: no-store and a content-length for the decoded body. A content blocker can match a response header by name, so an allowlist is what keeps anything naming Fingerly off the page.
client_ipis the one thing you must get right. Resolve it from a header your own infrastructure sets, such as your load balancer's or CDN's, and fall back topeer_host, the socket peer. Trust that header only when traffic can reach your app solely through that CDN or load balancer; otherwise a visitor can send it themselves. Never read the left-mostX-Forwarded-Forvalue: the visitor writes it. The callback is synchronous, because it is called under both standards.
The callback must return exactly one IPv4 or IPv6 address, such as 203.0.113.7 or 2001:db8::1. Anything else, including None, an empty string, a list, an address with a port, or an exception, is treated as a configuration mistake: the request is not forwarded, the visitor gets 500 with the one line The client IP callback returned no valid address, and the fingerly.proxy logger reports it once per process.
ProxyRequest gives the callback headers (case-insensitive), path, method, peer_host, mount and raw_path. peer_host is the socket peer, which is your load balancer rather than the visitor whenever one sits in front of you.
A note on mount paths
Both adapters match the path as the mounted application sees it: PATH_INFO under WSGI, and under ASGI the path with root_path removed when it is still carrying it. Mounted at its own path, the proxy finds that path in the mount instead, SCRIPT_NAME or root_path, with nothing after it.
That last part needs care. ASGI servers disagree about what path holds under a mount: Starlette 0.47 and newer leave it whole and report the prefix separately in root_path, while older versions and some routers strip the prefix off it. Both are permitted by the spec, so the proxy detects which one it was given rather than assuming.
Taking the application-relative path rather than the whole one is what makes a sub-URI deployment work. There, root_path or SCRIPT_NAME carries a prefix that belongs to the deployment and that your path knows nothing about, so a proxy matching on the whole path would refuse every request. It is the same rule Rack's PATH_INFO and ASP.NET Core's Request.Path already follow.
tests/test_frameworks.py drives real Starlette and Flask apps, mounted plainly and again under a sub-URI, to keep all of it that way.
The proxy opens its upstream connections on first use, one pool per standard. Close whichever you used when your app shuts down: proxy.close() for WSGI, await proxy.aclose() for ASGI. A WSGI process can simply exit.
upstream replaces the API origin for testing against a local API. It takes a scheme, a host and an optional port and nothing else: a path, query, fragment, credentials, space or control character is refused when the proxy is built. It must be https. Plain http is accepted only for 127.0.0.1, localhost or [::1], and only with allow_insecure_loopback=True, which is meant for local development and tests:
proxy = FingerlyProxy(
proxy_key=os.environ["FINGERLY_PROXY_KEY"],
path="/k7x2qm4a",
client_ip=lambda request: request.peer_host,
upstream="http://127.0.0.1:8080",
allow_insecure_loopback=True,
)Each guide is a complete app. Replace /k7x2qm4a with the path the dashboard issued, and set FINGERLY_SECRET_KEY and FINGERLY_PROXY_KEY. The browser posts identifications to the proxy path and sends the requestId it gets back to /verify/<request_id>, where your server reads the event with its secret key.
| Framework | Client | Proxy mounted with |
|---|---|---|
| FastAPI | AsyncFingerly, one per worker, built in the lifespan |
app.add_route with proxy.asgi |
| Django | Fingerly, one per process |
A wrapper in wsgi.py or asgi.py, before URL routing |
| Flask | Fingerly, one per process |
DispatcherMiddleware with proxy.wsgi |
Complete app
# main.py; run with: uvicorn main:app
import contextlib
import os
from fastapi import FastAPI, HTTPException, Request
from fingerly import (
AsyncFingerly,
FingerlyAPIError,
FingerlyEventPendingError,
FingerlyProxy,
)
proxy = FingerlyProxy(
proxy_key=os.environ["FINGERLY_PROXY_KEY"],
path="/k7x2qm4a",
client_ip=lambda request: (
request.headers.get("cf-connecting-ip") or request.peer_host
),
)
@contextlib.asynccontextmanager
async def lifespan(app: FastAPI):
# One read client per worker, built on the worker's own event loop.
app.state.fingerly = AsyncFingerly(secret_key=os.environ["FINGERLY_SECRET_KEY"])
yield
await app.state.fingerly.aclose()
await proxy.aclose()
app = FastAPI(lifespan=lifespan)
app.add_route("/k7x2qm4a", proxy.asgi)
@app.get("/verify/{request_id}")
async def verify(request_id: str, request: Request):
try:
event = await request.app.state.fingerly.events.get(request_id)
except FingerlyEventPendingError as error:
# Not decided yet, not fraud: ask the caller to come back.
retry_after = str(round(error.retry_after or 2))
raise HTTPException(503, headers={"Retry-After": retry_after}) from None
except FingerlyAPIError as error:
raise HTTPException(404 if error.status == 404 else 502) from None
return {
"identifiable": event.identifiable,
"visitor_id": event.visitor_id,
"suspect_score": event.suspect_score,
}The same works under uvicorn --workers 4 or gunicorn's uvicorn worker: each worker runs the lifespan and gets its own client and pool.
Django has no add_route, so put the proxy in front of Django in wsgi.py or asgi.py, before any URL routing. In a project named mysite:
Complete app (identification.py, wsgi.py, asgi.py, views.py, urls.py)
# mysite/identification.py
import os
from fingerly import Fingerly, FingerlyProxy
PROXY_PATH = "/k7x2qm4a"
proxy = FingerlyProxy(
proxy_key=os.environ["FINGERLY_PROXY_KEY"],
path=PROXY_PATH,
client_ip=lambda request: (
request.headers.get("cf-connecting-ip") or request.peer_host
),
)
# One read client per process, shared by every thread.
fingerly = Fingerly(secret_key=os.environ["FINGERLY_SECRET_KEY"])# mysite/wsgi.py, for gunicorn mysite.wsgi or runserver
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
from mysite.identification import PROXY_PATH, proxy # noqa: E402
django_application = get_wsgi_application()
def application(environ, start_response):
if environ.get("PATH_INFO") == PROXY_PATH:
return proxy.wsgi(environ, start_response)
return django_application(environ, start_response)# mysite/asgi.py, for uvicorn mysite.asgi:application
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
from mysite.identification import PROXY_PATH, proxy # noqa: E402
django_application = get_asgi_application()
async def application(scope, receive, send):
if scope["type"] == "http" and scope["path"] == PROXY_PATH:
await proxy.asgi(scope, receive, send)
else:
await django_application(scope, receive, send)# mysite/views.py
from django.http import JsonResponse
from fingerly import FingerlyAPIError, FingerlyEventPendingError
from mysite.identification import fingerly
def verify(request, request_id):
try:
event = fingerly.events.get(request_id)
except FingerlyEventPendingError as error:
# Not decided yet, not fraud: ask the caller to come back.
retry_after = str(round(error.retry_after or 2))
return JsonResponse(
{"error": error.code}, status=503, headers={"Retry-After": retry_after}
)
except FingerlyAPIError as error:
status = 404 if error.status == 404 else 502
return JsonResponse({"error": error.code}, status=status)
return JsonResponse(
{
"identifiable": event.identifiable,
"visitor_id": event.visitor_id,
"suspect_score": event.suspect_score,
}
)# mysite/urls.py
from django.urls import path
from mysite import views
urlpatterns = [path("verify/<str:request_id>", views.verify)]verify is a plain view, so Django runs it in a thread under ASGI too. In an async def view use AsyncFingerly instead, built once per process.
Complete app
# app.py; run with: gunicorn app:app, or flask --app app run
import os
from flask import Flask, abort
from werkzeug.middleware.dispatcher import DispatcherMiddleware
from fingerly import (
Fingerly,
FingerlyAPIError,
FingerlyEventPendingError,
FingerlyProxy,
)
app = Flask(__name__)
fingerly = Fingerly(secret_key=os.environ["FINGERLY_SECRET_KEY"])
proxy = FingerlyProxy(
proxy_key=os.environ["FINGERLY_PROXY_KEY"],
path="/k7x2qm4a",
client_ip=lambda request: (
request.headers.get("cf-connecting-ip") or request.peer_host
),
)
app.wsgi_app = DispatcherMiddleware(app.wsgi_app, {"/k7x2qm4a": proxy.wsgi})
@app.get("/verify/<request_id>")
def verify(request_id):
try:
event = fingerly.events.get(request_id)
except FingerlyEventPendingError as error:
# Not decided yet, not fraud: ask the caller to come back.
retry_after = str(round(error.retry_after or 2))
return {"error": error.code}, 503, {"Retry-After": retry_after}
except FingerlyAPIError as error:
abort(404 if error.status == 404 else 502)
return {
"identifiable": event.identifiable,
"visitor_id": event.visitor_id,
"suspect_score": event.suspect_score,
}A DispatcherMiddleware mount answers everything under its path too, which is what path narrows back down to the one path.
timeout is one deadline over the whole request: connecting, sending, the response headers and the body. An API that answers a byte at a time cannot stretch it. The default is 10 seconds for the clients and 5 for the proxy. Response bodies over 4 MiB are refused rather than buffered: the clients raise FingerlyAPIError with code response_too_large.
Under a thread or process server (gunicorn sync or gthread workers, Django or Flask under WSGI), size the pool for the slow case, not the average one: while Fingerly is slow, every proxied request holds its thread for the whole timeout. At 100 proxied requests a second with 1% of them running into a 5 second timeout, that is 5 threads busy on average, before any fast request is served. Run more threads than that, lower timeout for the proxy, or serve through proxy.asgi, where a waiting request holds no thread.
Each client, and each proxy handler, keeps its connections open between requests and shares them across threads or tasks. Up to 256 concurrent requests per process reuse connections rather than opening one each; pass limits=httpx.Limits(max_connections=…) to change that. Connections are replaced every five minutes, so a changed DNS answer is picked up. Redirects are never followed and no cookies are kept.
Pass api_version to select a route version, for example v1 (the default) or v2. The server must support the chosen version. The version applies to every API request; it is separate from the endpoint origin. On the proxy it selects the ingest URL, /api/v2/ingest, and nothing on your own site.
uv sync # 3.9 per .python-version, dev group included
uv run ruff check .
uv run ruff format --check .
uv run mypy
uv run pytest
uv run python scripts/sync_contract.py --check
uv build # wheel and sdistuv sync reads the dev dependency group, so there is nothing else to install. .python-version pins the development interpreter to 3.9, the oldest supported runtime, so the floor is exercised locally rather than only in CI. uv.lock is committed; CI installs with uv sync --frozen.
The vendored synthetic contract snapshot makes tests independent of sibling repositories. To update it from the integration workspace, set FINGERLY_CONTRACT_DIR to its contract directory and run python scripts/sync_contract.py. Checks verify the recorded hashes. Never put production secrets in fixtures.
Source structure
_client.py holds both clients and their event reads. _http.py is the connection pool both clients and the proxy send through, with its deadline and body cap. _transport.py builds requests and interprets responses, so the two clients share one definition of what a request is and what a failure means. _models.py owns Event, EventPage and their parsing. _enums.py holds the string enums the models and webhooks compare against. _webhooks.py verifies signatures. _proxy.py owns every proxy decision, with _asgi.py and _wsgi.py as thin adapters that only read a request and write a response, so the two standards cannot drift apart. _config.py validates every caller-supplied option: keys, origins, API versions and durations, all before any network access. _errors.py holds the exception hierarchy. _version.py holds the version everything else reads. __init__.py only exposes the public API.
- Python 3.9 or newer.
- One runtime dependency,
httpx(>=0.27,<1).
Open an issue on this repository, or write to support@fingerly.io. Security issues: security@fingerly.io.
Apache-2.0. See LICENSE.
