Skip to content

FastAPI: emit structured RequestHandled event per HTTP request - #202

Merged
tmgbedu merged 2 commits into
mainfrom
task/fastapi-lifecycle-events-1324
Jul 29, 2026
Merged

FastAPI: emit structured RequestHandled event per HTTP request#202
tmgbedu merged 2 commits into
mainfrom
task/fastapi-lifecycle-events-1324

Conversation

@tmgbedu

@tmgbedu tmgbedu commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

Summary

Implements task #1324 — Telescope-style visibility into FastAPI requests, scoped down to structured events only (no storage, no UI, no other watchers).

  • Adds RequestLifecycleMiddleware (fastapi_startkit/fastapi/middleware.py), registered automatically by FastAPIProvider.boot().
  • For every HTTP request it dispatches a RequestHandled event (fastapi_startkit/fastapi/events.py) through the existing Event dispatcher/facade from task #940 — no parallel event mechanism was built.
  • Payload: method, path, status_code, duration_ms, request_id.
  • No existing request-id/correlation-id mechanism was found in the framework, so one is generated per request (uuid4), or echoed back if the client already sent an X-Request-Id header. The id is also returned on the response via X-Request-Id.
  • Dispatch-only: this PR adds no listener beyond the test one that proves it fires. Application/logging listeners register the normal way via Event.listen(RequestHandled, ...).
  • Wrapped in try/finally so the event still fires (with status_code=500) even if an unhandled exception escapes the router.

Scope confirmation / overlap check

  • Task feat(process): add Process utility class with sync/async shell execution #104 (framework-native startup/shutdown lifecycle forwarding to FastAPI) — unrelated. That's about process-level on_event("startup"/"shutdown")/lifespan hooks (Application.add_event_handler), not per-request events. No overlap.
  • Task #1262 ("does FastAPI/fastapi_startkit emit lifecycle events?", body empty) — before this PR, no. This PR is effectively the answer/implementation: the framework now emits a structured per-request RequestHandled event via the Event dispatcher. Worth closing/merging #1262 into this PR's context.

Out of scope (left as extension points, not implemented)

  • DB query watcher, exception watcher, or any other Telescope-style watcher.
  • Storage backend / persistence of emitted events.
  • Any dashboard/UI.

Test plan

  • New test file tests/fastapi/test_request_lifecycle_events.py: boots a real Application + FastAPIProvider, hits real routes via TestClient, and asserts the event payload, the X-Request-Id header (generated + echoed), error-status propagation, and Event.fake() interception.
  • Full suite: uv run pytest --ignore=tests/masoniteorm/postgres → 2046 passed, 7 skipped.
  • ruff check / ruff format --check clean.

Adds RequestLifecycleMiddleware to the FastAPI integration, registered
automatically by FastAPIProvider. For every request it fires a
RequestHandled event (method, path, status_code, duration_ms, request_id)
through the existing Event dispatcher/facade — no new event mechanism,
no storage, no UI. A request id is generated per request (or echoed back
if the client already sent one) and returned via the X-Request-Id header.
@codecov

codecov Bot commented Jul 29, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

A bare (non-HTTPException) exception is handled by Starlette's
ServerErrorMiddleware, which sits outside RequestLifecycleMiddleware —
so the middleware's local response stays None on that path and the
header never gets set there. HTTPException stays inside the middleware
via ExceptionMiddleware and was already fine.

Stamp the header from the shared exception handler instead (covers
Exception, HTTPException, and RequestValidationError alike), using the
request_id RequestLifecycleMiddleware already stashed on request.state
before the route ran. This keeps the RequestHandled event's request_id
correlated with the response the client actually receives, including
on the 500 path.
@tmgbedu
tmgbedu merged commit 3319171 into main Jul 29, 2026
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant