# WatchTower15 in FastAPI

```sh
pip install "watchtower15[fastapi]"
```

```python
from fastapi import Depends, FastAPI
from watchtower15 import AsyncClient
from watchtower15.integrations.fastapi import WatchTower15

wt15 = WatchTower15(app_info="billing/2.4.1", allow_list={"orders.created": "count"})
app = FastAPI(lifespan=wt15.lifespan)

@app.get("/servers")
async def servers(client: AsyncClient = Depends(wt15.client)):
    return [s.name async for s in client.servers.list(limit=50)]

@app.post("/orders")
def create_order():
    wt15.aggregator.increment("orders.created")
```

`WatchTower15(...)` takes the credentials and URLs (each left out is read from the `WT15_*` variables), `app_info`, `allow_list`, `heartbeat`, `enabled`, `flush` (`background` or `per_request`) and `fake`. It builds nothing until it is used.

-   **`wt15.client`** is a dependency returning the shared `AsyncClient`, built at first use.
-   **`wt15.aggregator`** is the shared [aggregator](https://developer.watchtower15.com/sdks/python/metrics/), on a sync `Client` of its own that holds the metrics token alone (the aggregator’s thread cannot use an `AsyncClient`). `increment()` only updates memory, so it is safe in an `async def` handler.
-   **`wt15.lifespan`** closes what was built when the app shuts down: the aggregator and the log handlers within 10 seconds, off the event loop, then the `AsyncClient`. If your app has a lifespan, wrap it: `FastAPI(lifespan=wt15.lifespan_around(my_lifespan))`; ours is entered first and left last.

## Logs

Attach a [`WatchTower15Handler`](https://developer.watchtower15.com/sdks/python/logs/) to the loggers you want shipped. With no client given it builds `Client.from_environment()` at its first flush:

```python
import logging
from watchtower15.integrations.logging import WatchTower15Handler

logging.getLogger("billing").addHandler(WatchTower15Handler(stream="billing"))
```

## Serverless: per-request flushing

With `flush="per_request"` the aggregator starts no thread, and the ASGI middleware flushes after each HTTP request, in a worker thread it waits for, so a Lambda invocation (with Mangum) ends after the flush:

```python
wt15 = WatchTower15(flush="per_request", allow_list={"orders.created": "count"})
app.add_middleware(WatchTower15Middleware, wt15=wt15)   # from watchtower15.integrations.fastapi
```

See [servers, workers and serverless](https://developer.watchtower15.com/sdks/python/deployment/).

## Tests

`WatchTower15(fake=True)` hands out an `AsyncFakeClient` and a `FakeAggregator`: nothing leaves the process and no credential is needed. See [testing](https://developer.watchtower15.com/sdks/python/testing/).

Source: https://developer.watchtower15.com/sdks/python/fastapi/
