# FastAPI (Python)

> Add ScreenlyyID identity verification to a FastAPI back end: create a session, then read the result after the hosted page reports it is done.

Canonical URL: https://www.screenlyyid.com/docs/recipes/fastapi/

A FastAPI app with the two routes a ScreenlyyID integration needs. The API key and the `CorrelationId` stay on the server; your front end or app only receives a `verificationId` and the hosted page URL. Python 3.9 or later.

| Route | What it does |
|---|---|
| `POST /api/verifications` | Step 1: calls [`instance/create`](https://www.screenlyyid.com/docs/authentication/create-instance/) and returns `{ verificationId, webEnrolmentUrl }`. |
| `GET /api/verifications/{id}` | Step 4: after the front end receives `IDV_SESSION_COMPLETE`, reads the result once with [`document/result`](https://www.screenlyyid.com/docs/api-reference/hosted-sdk-data/get-decision-result/). |

## Install
```bash
pip install fastapi uvicorn httpx
export SCREENLYYID_API_KEY=test_xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
```

Create a test key first: see [Get a test key](https://www.screenlyyid.com/docs/ai-quickstart/#get-a-test-key).

## main.py
```python
"""FastAPI back end for ScreenlyyID identity verification. Python 3.9 or later.

The API key and the CorrelationId stay on this server: the browser or app only gets a verification_id and the hosted page URL.
Run: SCREENLYYID_API_KEY=test_... uvicorn main:app
"""
import os
import uuid

import httpx
from fastapi import FastAPI, HTTPException

API = "https://api.screenlyyid.com"
API_KEY = os.environ["SCREENLYYID_API_KEY"]  # a test_ key while you build

app = FastAPI()
# verification_id -> {"user_id": ..., "correlation_id": ...}. In memory for the example; use your database.
sessions: dict = {}


def current_user_id() -> str:
    return "demo-user"  # replace with your own authentication


@app.post("/api/verifications", status_code=201)
async def create_verification():
    """Step 1: create a verification session (server side)."""
    async with httpx.AsyncClient(timeout=30) as client:
        r = await client.post(
            f"{API}/api/v1/instance/create",
            headers={"x-api-key": API_KEY},
            json={"GlobalScreening": ["idv"], "CustomerIntelligence": []},
        )
    if r.status_code != 200:
        raise HTTPException(502, f"ScreenlyyID instance/create failed (HTTP {r.status_code})")
    body = r.json()  # the property names are exactly CorrelationId and webEnrolmentUrl
    verification_id = str(uuid.uuid4())
    sessions[verification_id] = {"user_id": current_user_id(), "correlation_id": body["CorrelationId"]}
    return {"verificationId": verification_id, "webEnrolmentUrl": body["webEnrolmentUrl"]}  # no CorrelationId


@app.get("/api/verifications/{verification_id}")
async def get_verification(verification_id: str):
    """Step 4: after the browser or app reports IDV_SESSION_COMPLETE, read the result once."""
    session = sessions.get(verification_id)
    if not session or session["user_id"] != current_user_id():
        raise HTTPException(404, "Unknown verification")
    async with httpx.AsyncClient(timeout=30) as client:
        r = await client.get(
            f"{API}/api/v1/document/result",
            headers={"x-api-key": API_KEY, "x-correlation-id": session["correlation_id"]},
        )
    if r.status_code == 200:
        return {"status": "ready", "result": r.json()}
    if r.status_code == 500:  # asked before the capture finished
        return {"status": "pending"}
    raise HTTPException(502, f"ScreenlyyID document/result failed (HTTP {r.status_code})")
```

## Run and test
```bash
uvicorn main:app --port 3000
```

```bash
curl -s -X POST localhost:3000/api/verifications
# {"verificationId":"...","webEnrolmentUrl":"https://app.screenlyyid.com/idv/..."}

curl -s localhost:3000/api/verifications/VERIFICATION_ID
# {"status":"pending"}   (asked before the person has finished the capture)
```

Open `webEnrolmentUrl` in a browser or embed it as described in [Web app](https://www.screenlyyid.com/docs/integrations/web-app/). When the page reports `IDV_SESSION_COMPLETE`, the same `GET` returns `{"status":"ready","result":{...}}`.

The front end is the same as for any web app: embed `webEnrolmentUrl` in an iframe with `allow="camera; microphone"`, listen for the event, then call your `GET` route. See [Web app](https://www.screenlyyid.com/docs/integrations/web-app/). For a mobile app, see the [iOS recipe](https://www.screenlyyid.com/docs/recipes/ios/).

**Run it from the repo:** this is the code in [`fastapi/`](https://github.com/ScreenlyyID/examples/tree/main/fastapi) of the public examples repo ([ScreenlyyID/examples](https://github.com/ScreenlyyID/examples)), which has a README and an `.env.example`.

## What this does not include

- **Your own sign-in.** The sample uses a fixed `demo-user`. Replace it with your authentication, and keep the check that a verification belongs to the person asking.
- **A database.** Sessions are kept in memory so the sample stays short. Store the `CorrelationId` against your user in your database.
- **HTTPS and rate limits.** Add both before this faces the internet.

See the [AI quickstart](https://www.screenlyyid.com/docs/ai-quickstart/) for the full API flow and the [error table](https://www.screenlyyid.com/docs/ai-quickstart/#errors).
