> ## Documentation Index
> Fetch the complete documentation index at: https://www.courier.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> Install the Courier skill before writing code: `npx skills add trycourier/courier-skills`. It carries the verified SDK shapes and the rules you cannot get wrong.
> Authenticate every request with `Authorization: Bearer <API_KEY>`. A workspace has several environments and each has its own keys, which are plain `pk_` strings with no environment prefix. Start with Test.
> Send with `client.send.message` from the Node SDK (`@trycourier/courier` v7 and later, where the client is the default import). Reference a template by its `nt_` id or its alias.
> A send accepts a bare Elemental element list, but storing content on a template requires the top-level elements wrapped in a channel element.
> To translate a template, write one locale at a time with `PUT /notifications/{id}/locales/{localeId}`, which merges into the existing translations. `PUT /notifications/{id}/content` and `PUT /notifications/{id}/elements/{elementId}` overwrite translations along with the content, so send each element's `id` and `locales` back, and first remove every `checksum` and any `locales` key that starts with an underscore.
> Templates and journeys can be built in the Courier app or created through the API. Either way they live in the workspace and are referenced by ID when you send.
> The hosted MCP server is https://mcp.courier.com. For a briefing on what Courier is and when to use it, read https://www.courier.com/llms.txt.
> Adding notifications to a framework app? Start from its quickstart, which has a runnable repo and complete files: Next.js email https://www.courier.com/docs/guides/add-transactional-email-to-nextjs.md, Django https://www.courier.com/docs/guides/add-notifications-to-django.md, Rails https://www.courier.com/docs/guides/add-notifications-to-rails.md, Node.js digest https://www.courier.com/docs/guides/batch-notifications-into-a-daily-digest-in-node.md, Laravel https://www.courier.com/docs/guides/add-notifications-to-laravel.md, FastAPI https://www.courier.com/docs/guides/send-notifications-from-fastapi.md, Express https://www.courier.com/docs/guides/add-notifications-to-express.md, and the React, Next.js, Astro, and Nuxt inbox quickstarts under /guides/add-an-inbox-to-*.
> Prefer the Guides tab for how-do-I questions and the Docs tab for how-does-it-behave questions. The API reference lives under /api-reference.

# Send notifications from a FastAPI app

> Send email and in-app notifications from a FastAPI app with Courier. Queue sends in background tasks and notify users when an AI agent task finishes.

Add email and in-app notifications to a FastAPI app by queuing Courier sends in background tasks. When an AI agent task finishes, one `client.send.message` call emails the user and puts the result in their inbox.

```python theme={null}
import os

from courier import Courier

client = Courier(api_key=os.environ["COURIER_API_KEY"])

response = client.send.message(
    message={
        "to": {"email": os.environ["DEMO_EMAIL"]},
        "content": {"title": "Your agent run finished", "body": "Sent from FastAPI with Courier."},
        "routing": {"method": "single", "channels": ["email"]},
    },
)
print(response.request_id)
```

Save it as `first_send.py`, then run it with your API key and email address:

```bash theme={null}
python3 -m venv .venv && source .venv/bin/activate
pip install trycourier && COURIER_API_KEY=YOUR_COURIER_API_KEY DEMO_EMAIL=YOUR_EMAIL python first_send.py
```

It prints a request id to find in [Courier Logs](https://app.courier.com/logs). On a Test key, send to your Courier login address, which [test email](https://www.courier.com/docs/workspaces/environments.md#email-in-the-test-environment) reaches with no provider connected.

> [card] [courier-fastapi-quickstart](https://github.com/trycourier/courier-fastapi-quickstart)
>
> The finished FastAPI app from this guide, ready to clone and run.

## Build this with a coding agent

To have a coding agent add Courier to your FastAPI app, paste this prompt into Claude Code, Cursor, or Codex from the project root:

```text theme={null}
Add notifications to this FastAPI app with Courier, including an email and inbox notification when an AI agent run finishes.
Follow https://www.courier.com/docs/guides/send-notifications-from-fastapi.md and the reference app at https://github.com/trycourier/courier-fastapi-quickstart.
Use the trycourier package (from courier import AsyncCourier) and read COURIER_API_KEY from the environment.
Queue every send with BackgroundTasks so the response returns first, and pass one idempotency key per event, such as agent-run-<run_id>-finished.
Route the agent-run notification to email and inbox together, and keep our existing email provider.
When done, add a demo command like the reference app's demo.py, run it, and show me the request id.
```

Install the Courier skill with `npx skills add trycourier/courier-skills`, and connect the [Courier MCP server](https://www.courier.com/docs/resources/mcp.md) so the agent can check Courier Logs and templates itself.

### Rules for AI agents

* Use `trycourier` (`from courier import AsyncCourier`), with one client created in the `main.py` lifespan.
* Read `COURIER_API_KEY` from the server's environment, and never hard-code it.
* Queue each send with `background_tasks.add_task`, so the response returns first.
* Pass one `idempotency_key` per event: `welcome-<user_id>` per saved user, `agent-run-<run_id>-finished` per run.
* Route a finished run to `["email", "inbox"]` with `"method": "all"`, for the user from `current_user`, never the request body.
* Catch `CourierError` in `send()` and log it with the key, because the SDK already [retried what Courier runs again](https://www.courier.com/docs/reference/api-overview.md#retry-a-request-safely).

## What you'll build

This FastAPI app has three routes, and each Courier send runs in a background task:

* **A welcome email** from `POST /signup`, which returns `202` right away
* **An email and an inbox message** when a simulated agent run finishes
* **A `GET /agent-runs/{run_id}` route** that returns the summary and Courier request id

Tested in November 2026 with FastAPI 0.165, trycourier 10.2.0, and Python 3.12.

## Prerequisites

### For the first send

* [A Courier API key](https://app.courier.com/settings/api-keys)
* Python 3.12 or newer

### For the full build

* A FastAPI project

## Clone the finished FastAPI app

Clone the Courier FastAPI quickstart to run the finished app with your own key:

```bash theme={null}
git clone https://github.com/trycourier/courier-fastapi-quickstart.git
cd courier-fastapi-quickstart
python3 -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt
cp .env.example .env   # add your API key and your email address
python demo.py
```

The steps below add or change these files:

| File | What it does |
| :- | :- |
| `requirements.txt` | FastAPI, `trycourier`, and `python-dotenv` |
| `notifications.py` | The Courier sends |
| `agent.py` | Runs the agent, then notifies the user |
| `main.py` | The client, the demo user, and the routes |

## Install the Courier Python SDK in FastAPI

The Courier Python SDK is `trycourier` on PyPI, and its async client, `AsyncCourier`, suits FastAPI. Add it to `requirements.txt` with FastAPI and `python-dotenv`:

```text requirements.txt theme={null}
fastapi[standard]~=0.165
trycourier~=10.2
python-dotenv~=1.2
```

Install them in a virtualenv:

```bash theme={null}
python3 -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt
```

Create `.env` next to `main.py` with your key and address:

```bash .env theme={null}
COURIER_API_KEY=YOUR_COURIER_API_KEY
DEMO_EMAIL=YOUR_EMAIL
```

## Write the Courier send functions for FastAPI

`notifications.py` holds every Courier call in the FastAPI app. Each one is [`POST /send`](https://www.courier.com/docs/api-reference/send/send-a-message) with an idempotency key, and `inbox` delivers to the [Courier inbox](https://www.courier.com/docs/in-app/send-to-the-inbox.md) of the `user_id` in `to`.

```python notifications.py lines theme={null}
import logging

from courier import AsyncCourier, CourierError

logger = logging.getLogger(__name__)


async def send(courier: AsyncCourier, message: dict, idempotency_key: str) -> str | None:
    """Send one message through Courier. Returns the request id, or None if the send failed."""
    try:
        response = await courier.send.message(message=message, idempotency_key=idempotency_key)
    except CourierError:
        # A background task has no caller to raise to, so log the failure with its key.
        logger.exception("Courier send failed, idempotency key %s", idempotency_key)
        return None
    logger.info("Courier accepted %s, request id %s", idempotency_key, response.request_id)
    return response.request_id


async def send_welcome_email(courier: AsyncCourier, user_id: str, email: str, name: str) -> str | None:
    return await send(
        courier,
        message={
            "to": {"user_id": user_id, "email": email},
            "content": {"title": "Welcome to Acme, {{name}}", "body": "Your account is ready."},
            "routing": {"method": "single", "channels": ["email"]},
            "data": {"name": name},
        },
        # Pass your saved user's id, so a repeat signup for the same user reuses the key.
        idempotency_key=f"welcome-{user_id}",
    )


async def notify_agent_run_finished(
    courier: AsyncCourier, user_id: str, email: str, run_id: str, summary: str
) -> str | None:
    return await send(
        courier,
        message={
            "to": {"user_id": user_id, "email": email},
            # The summary goes in data, so text the agent wrote is never read as a template.
            "content": {"title": "Your agent run finished", "body": "{{summary}}"},
            # Email and the Courier inbox at once. The inbox shows it to user_id.
            "routing": {"method": "all", "channels": ["email", "inbox"]},
            "data": {"summary": summary, "run_id": run_id},
        },
        # One key per run, so a retry can't notify twice and the next run still sends.
        idempotency_key=f"agent-run-{run_id}-finished",
    )
```

**A failed send in a background task is logged, because no caller is waiting for it.** `send()` returns `None` after the SDK retries [what Courier runs again](https://www.courier.com/docs/reference/api-overview.md#retry-a-request-safely).

## Notify the user from FastAPI when an AI agent task finishes

In FastAPI, `run_and_notify` runs the agent in a background task, then notifies the user through Courier, so the request that starts the run returns at once.

```python agent.py lines theme={null}
import asyncio

from courier import AsyncCourier

from notifications import notify_agent_run_finished

# Runs live in memory for the demo. Use your database, because a dict is lost on restart.
RUNS: dict[str, dict] = {}


async def run_agent(prompt: str) -> str:
    """Stand-in for your agent. Replace it with your agent framework's call."""
    await asyncio.sleep(3)
    return f"Done: {prompt}. Found 3 themes and drafted a summary for review."


async def run_and_notify(courier: AsyncCourier, run_id: str, user_id: str, email: str, prompt: str) -> None:
    """Run the agent, then tell the user it finished. FastAPI runs this as a background task."""
    try:
        summary = await run_agent(prompt)
    except Exception:
        # A failed run notifies nobody. Send a "run failed" message the same way if you need one.
        RUNS[run_id]["status"] = "failed"
        raise
    RUNS[run_id].update(status="finished", summary=summary)
    # None when the send failed. send() in notifications.py logged why.
    RUNS[run_id]["request_id"] = await notify_agent_run_finished(courier, user_id, email, run_id, summary)
```

## Queue Courier notifications from FastAPI routes with BackgroundTasks

`main.py` creates one `AsyncCourier` client in the FastAPI lifespan and hands it to each sending route with `Depends`. Both POST routes queue their send with `BackgroundTasks` and return `202`.

```python main.py lines theme={null}
import logging
import os
import uuid
from contextlib import asynccontextmanager
from pathlib import Path
from typing import Annotated

from courier import AsyncCourier
from dotenv import load_dotenv
from fastapi import BackgroundTasks, Depends, FastAPI, HTTPException, Request
from pydantic import BaseModel

from agent import RUNS, run_and_notify
from notifications import send_welcome_email

# Load this project's .env only. A bare load_dotenv() also searches parent folders.
load_dotenv(Path(__file__).parent / ".env")
logging.basicConfig(level=logging.INFO)


@asynccontextmanager
async def lifespan(app: FastAPI):
    # Check the key at startup, before any request does per-user work.
    api_key = os.environ.get("COURIER_API_KEY")
    if not api_key:
        raise RuntimeError("COURIER_API_KEY is not set. Create .env with COURIER_API_KEY.")
    # One client for the app's lifetime, closed on shutdown.
    async with AsyncCourier(api_key=api_key) as courier:
        app.state.courier = courier
        yield


app = FastAPI(lifespan=lifespan)


def get_courier(request: Request) -> AsyncCourier:
    return request.app.state.courier


class User(BaseModel):
    id: str
    email: str


def current_user() -> User:
    # A demo user, so you can try this without auth. Read the signed-in user
    # from your session or database here.
    email = os.environ.get("DEMO_EMAIL")
    if not email:
        raise HTTPException(500, "DEMO_EMAIL is not set. Put your own email address in .env.")
    return User(id="user_123", email=email)


class Signup(BaseModel):
    name: str
    email: str


class AgentRunRequest(BaseModel):
    prompt: str


@app.post("/signup", status_code=202)
async def signup(
    body: Signup,
    background_tasks: BackgroundTasks,
    courier: Annotated[AsyncCourier, Depends(get_courier)],
):
    # Use your saved user's database id, so a repeat signup repeats its welcome key.
    user_id = f"user_{uuid.uuid4().hex}"
    # Runs after the response is sent, so signup never waits on Courier.
    background_tasks.add_task(send_welcome_email, courier, user_id, body.email, body.name)
    return {"user_id": user_id}


@app.post("/agent-runs", status_code=202)
async def start_agent_run(
    body: AgentRunRequest,
    background_tasks: BackgroundTasks,
    user: Annotated[User, Depends(current_user)],
    courier: Annotated[AsyncCourier, Depends(get_courier)],
):
    run_id = uuid.uuid4().hex
    RUNS[run_id] = {"id": run_id, "user_id": user.id, "status": "running", "summary": None, "request_id": None}
    # The response returns now. The run, then its notification, happen after it.
    background_tasks.add_task(run_and_notify, courier, run_id, user.id, user.email, body.prompt)
    return RUNS[run_id]


@app.get("/agent-runs/{run_id}")
async def get_agent_run(run_id: str, user: Annotated[User, Depends(current_user)]):
    run = RUNS.get(run_id)
    # Only the user who started a run can read it.
    if run is None or run["user_id"] != user.id:
        raise HTTPException(404, "Run not found")
    return run
```

**Take the user from your session, never from the request.** Replace `current_user`, which returns the demo user `user_123`, with your auth dependency.

## Verify

Start one FastAPI agent run, then find its Courier notification in [Logs](https://app.courier.com/logs). In the cloned repo, [`python demo.py`](https://github.com/trycourier/courier-fastapi-quickstart/blob/main/demo.py) starts a run, waits for it to finish, and prints the request id, with no server running.

In your own app, run `fastapi dev main.py` and start a run:

```bash theme={null}
curl -s -X POST localhost:8000/agent-runs -H "Content-Type: application/json" -d '{"prompt": "Summarize the open support tickets"}'
```

After about five seconds, read the run back by its `id` to get Courier's request id:

```bash theme={null}
curl -s localhost:8000/agent-runs/RUN_ID
```

```text theme={null}
{"id":"4e5d0a95dfd8...","user_id":"user_123","status":"finished","summary":"Done: Summarize the open support tickets. ...","request_id":"1-6740a1b2-..."}
```

Open the request id in Logs to see an email and an inbox delivery. To show the inbox in your app, [add an inbox](https://www.courier.com/docs/in-app/add-an-inbox.md) signed in as `user_123`.

| What you see | Fix |
| :- | :- |
| `AuthenticationError` 401 in the log | Use the key for this environment |
| `"request_id": null` on a finished run | Read the `Courier send failed` log line |
| Email arrives, inbox stays empty | Sign the inbox in as the send's `user_id` |

## Go to production with Courier

Courier is notification infrastructure for humans and AI agents. [Go live](https://www.courier.com/docs/guides/go-live.md) moves your FastAPI app from Test to Production:

* **Switch keys.** Set a Production `COURIER_API_KEY` and connect your email provider there.
* **Move long runs to a worker.** Run long agent tasks in a worker, such as Celery or arq, or a restart loses the run and its notification.
* **Honor opt-outs.** Map the notification to a subscription topic so users can mute agent updates in a [preference center](https://www.courier.com/docs/guides/build-a-preference-center.md).

| Task | Calling an email provider directly | With Courier |
| :- | :- | :- |
| In-app notifications | Build a feed, storage, and UI | Add `"inbox"` to `routing.channels` |
| Duplicates on retry | Your own dedupe table | An [idempotency key](https://www.courier.com/docs/reference/api-overview.md#retry-a-request-safely) per event |
| Opt-outs | Your own preference storage | [Preferences](https://www.courier.com/docs/recipients/preferences/overview.md) |
| One log | Each provider's dashboard | [Logs](https://www.courier.com/docs/monitor/logs.md) |

## FAQ

> [accordion] How do I send email from FastAPI?
>
> Sending email from FastAPI takes one `await client.send.message(...)` call on Courier's `AsyncCourier` client. Courier delivers it through the provider you connect, such as SendGrid, Amazon SES, or Resend.

> [accordion] Should I send notifications in a FastAPI background task?
>
> A FastAPI background task suits a Courier send, because the response goes out first. For sends that must survive a restart, use a worker such as Celery or arq, which can [retry with the same key](https://www.courier.com/docs/reference/api-overview.md#retry-a-request-safely).

> [accordion] How do I notify a user when an AI agent task finishes?
>
> Notifying a user when an AI agent task finishes takes one Courier send at the end of the task, routed to email and inbox with `"method": "all"`. Key it `agent-run-<run_id>-finished` so a retried task notifies once.

> [accordion] Can I use this with Flask?
>
> Flask sends through Courier with the synchronous `Courier` client from `first_send.py` and the same `message` and `idempotency_key`. A send in a Flask view waits for Courier, so queue it with Celery or RQ in production.
