Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event Handler on FastAPI

Tags:

fastapi

I'm investigating the best web framework for my purposes.

We'll develop several microservices, and we need to dispatch events on some microservices, that could be listened on other microservices.

Is there any support for that using FastAPI? If not, is there a way to listen db event operations? I saw the @app.on_event("shutdown|startup") from starlette, but can I dispatch more events?

Thank you in advance.

like image 424
Marcelo Trylesinski Avatar asked Aug 31 '25 22:08

Marcelo Trylesinski


2 Answers

Currently there are no generalised event dispatching/listening features in FastAPI.

@app.on_event("shutdown|startup")

Are a subsection on the ASGI protocol. Implemented by Starlette and in turn available in FastAPI

https://asgi.readthedocs.io/en/latest/specs/lifespan.html

FastApi/Starlette are web frameworks only and limited to http and websocket events they don't provide pre-built event handlers for any specific database events.

like image 129
user368604 Avatar answered Sep 05 '25 03:09

user368604


While FastAPI doesn't support general event dispatching, there are libraries available to supplement this. The one I've been using is fastapi-events (Disclaimer: I'm the maintainer)

Events can be dispatched by using dispatch("event name", {"payload": "here"})

The handling of events can be done either within the code, or be forwarded to a remote queue.

like image 21
melvin Avatar answered Sep 05 '25 03:09

melvin