# FastAPI

URL: https://iscredible.com/docs/integrations/fastapi

> Protect FastAPI signup endpoints and expensive routes with the async Python client.

Use the async client in FastAPI, and call it from the endpoint that creates accounts or runs expensive work.

## Install

```bash
pip install is-credible
```

Add `ISCREDIBLE_API_KEY` to your server's environment. `AsyncIsCredible` runs requests in a worker thread, so it needs no extra HTTP library.

## A small helper

app/risk.py:

```python
import logging
import os

from iscredible import AsyncIsCredible, IsCredibleError, decide

log = logging.getLogger(__name__)
client = AsyncIsCredible(api_key=os.environ["ISCREDIBLE_API_KEY"], timeout=3, max_retries=1)

async def screen(data, scenario_id=None):
    """Returns APPROVE, REVIEW or DENY. Returns APPROVE when the check can't run (fail open)."""
    try:
        action, _reasons = decide(await client.verify(data, scenario_id=scenario_id))
        return action
    except IsCredibleError as error:
        if error.status == 402:
            log.error("isCredible: no active plan, checks are paused (%s)", error.code)
        elif error.status == 429:
            log.warning("isCredible: rate limit or daily quota reached")
        else:
            log.warning("isCredible unavailable, allowing the request: %s", error)
    except ValueError as error:  # invalid input, e.g. a malformed email
        log.warning("isCredible input rejected: %s", error)
    return "APPROVE"
```

## Protect the signup endpoint

app/main.py:

```python
from fastapi import FastAPI, HTTPException, Request
from pydantic import BaseModel

from .risk import screen

app = FastAPI()

class Signup(BaseModel):
    email: str
    password: str
    device_id: str | None = None

@app.post("/signup")
async def signup(body: Signup, request: Request):
    action = await screen({
        "email": body.email,
        "ip": request.client.host if request.client else None,
        "userAgent": request.headers.get("user-agent"),
        "deviceId": body.device_id,
        "accountCreation": True,
    })

    if action == "DENY":
        raise HTTPException(status_code=403, detail="We couldn't create your account.")

    user = await create_user(body.email, body.password, needs_verification=(action == "REVIEW"))
    return {"id": user.id}
```

Behind a proxy or load balancer, start Uvicorn with `--proxy-headers` and set `--forwarded-allow-ips` to your proxy's address, so `request.client.host` is the user's IP and not the proxy's. Never send the password to isCredible.

## Protect expensive endpoints

Check usage before costly work such as AI calls. `check_usage` caches each answer and only calls the API when a check is due, so a dependency that runs on every request stays cheap.

```python
from fastapi import Depends, HTTPException, Request
from iscredible import IsCredibleError

from .risk import client

async def within_free_tier(request: Request, user=Depends(current_user)):
    try:
        decision = await client.check_usage(
            str(user.id),
            {"metric": "ai_tokens", "used": await tokens_used_this_month(user), "limit": 100000},
            {"ip": request.client.host if request.client else None},
        )
    except IsCredibleError:
        return  # fail open
    if decision["action"] == "DENY":
        raise HTTPException(status_code=429, detail="Free limit reached")

@app.post("/generate", dependencies=[Depends(within_free_tier)])
async def generate(...):
    ...
```

## Acting on the decision

| Decision | Suggested action |
|---|---|
| APPROVE | Create the account |
| REVIEW | Create it, but hold back free credits or API keys until the email or phone is verified |
| DENY | Return a neutral error. Don't say which check fired |

## Errors and limits

| Situation | What to do |
|---|---|
| Timeout, network error or 5xx | The SDK retries, then raises `IsCredibleError`. Fail open and log it |
| `429` rate limit or daily quota | The SDK retries with backoff, then raises. Fail open, and upgrade if it happens every day |
| `402` with `code` `trial_ended` or `subscription_ended` | Your account has no active plan. Fail open and choose a plan in the dashboard |
| `401` or `403` | The key is wrong, revoked or missing. Fix it; fail open meanwhile |

See the [Python SDK](https://iscredible.com/docs/sdks/python) for every option.
