# Upcoming transits in FastAPI: one shared async client

> FastAPI is async, so the AstroNode call has to be async too. This page wires one `httpx.AsyncClient` into the app's lifespan, exposes the transit-events endpoint as a typed route, and shows the event list it returned for the next three months.

Source: https://astronode.dev/integrations/fastapi · Updated: 2026-12-01

**How this page was verified:** **The FastAPI/httpx code was not executed** - neither package is installed on the build machine and nothing was installed for this page. The AstroNode request it makes (same URL, headers and JSON body) was executed with Python's standard-library `urllib` against the in-memory API; the events table is that response.

## One client for the app's lifetime

`main.py` - `pip install fastapi httpx`, key in the environment:

```python
import os
from contextlib import asynccontextmanager
from datetime import date

import httpx
from fastapi import FastAPI, HTTPException, Query

ASTRONODE = os.environ.get("ASTRONODE_BASE_URL", "https://api.astronode.dev")


@asynccontextmanager
async def lifespan(app: FastAPI):
    app.state.astronode = httpx.AsyncClient(
        base_url=ASTRONODE,
        headers={"Authorization": f"Bearer {os.environ['ASTRONODE_API_KEY']}"},
        timeout=15.0,
    )
    yield
    await app.state.astronode.aclose()


app = FastAPI(lifespan=lifespan)


@app.get("/transits")
async def transits(
    start: date,
    end: date,
    planets: list[str] = Query(default=["Saturn", "Jupiter", "Mars"]),
):
    res = await app.state.astronode.post(
        "/v1/transits/events",
        json={"from": start.isoformat(), "to": end.isoformat(), "planets": planets},
    )
    body = res.json()
    if res.is_error:
        raise HTTPException(status_code=res.status_code if res.status_code < 500 else 502, detail=body["error"])
    return [
        {"at": e["at"], "planet": e["planet"], "kind": e["kind"], "sign": e["sign"]}
        for e in body["data"]["events"]
    ]
```

The request field is called `from`, which is a Python keyword - so the route takes `start`/`end` and renames them in the JSON body. FastAPI validates both as dates, and AstroNode rejects an unknown planet name (the nine grahas, capitalised) with a `400` whose `details` the route passes through.

## What it returned

*Events for Saturn, Jupiter and Mars, 1 Dec 2026 - 1 Mar 2027*

| `at` | Planet | `kind` | Sign |
| --- | --- | --- | --- |
| 2026-12-12 | Saturn | `retrograde_end` | Pisces |
| 2026-12-14 | Jupiter | `retrograde_start` | Leo |
| 2027-01-11 | Mars | `retrograde_start` | Leo |
| 2027-01-25 | Jupiter | `sign_change` (Leo → Cancer) | Cancer |
| 2027-01-25 | Jupiter | `exalt_start` | Cancer |

Positions are sidereal (Lahiri), so these are Vedic sign ingresses - Jupiter re-entering Cancer while retrograde, where it is exalted. The engine samples each planet every `step_days` (default 1) and stamps an event at the first sample where the state changed, so `at` is accurate to the step: to the day here. The response also includes `initial_states` (each planet's sign and retrograde/combust flags at `from`), which is what a "right now" banner should read.

## The mistake that bites first: a blocking call in async def

`requests.post(...)` inside an `async def` route works in testing and then stalls production: it blocks the event loop for the whole round trip, so every other request on that worker waits too. Either use an async client (as above), or declare the route with plain `def` so FastAPI runs it in its threadpool.

- Create the `AsyncClient` once (lifespan), not per request - a new client per call throws away connection pooling and TLS reuse.
- Give it an explicit `timeout`; on `httpx.TimeoutException` return a 504 of your own rather than letting the exception become a 500.
- A 429 from AstroNode carries `Retry-After`; for a page users are waiting on, surface it rather than sleeping inside the request ([RATE_LIMITED](https://astronode.dev/docs/errors/rate-limited)).

## Questions

**Which AstroNode endpoints does the FastAPI example call?**

1 endpoint: Transit Events (Gochar) (`POST /v1/transits/events`).

**Was the FastAPI code on this page actually run?**

**The FastAPI/httpx code was not executed** - neither package is installed on the build machine and nothing was installed for this page. The AstroNode request it makes (same URL, headers and JSON body) was executed with Python's standard-library `urllib` against the in-memory API; the events table is that response.

## Endpoints

- [`POST /v1/transits/events`](https://astronode.dev/capabilities/vedic/transits-events) - Transit Events (Gochar) API
