Is there a way to call an api directly in fastapi whenever backend server starts?

Viewed 1613

So i have an API which updates weather data in db every hour(using repeat_every decorator). Is there a way to call this API automatically whenever back-end server is up and running instead of manually calling it?

1 Answers

Yes there is. You can define event handlers (functions) that need to be executed before the application starts up and shutting down.

You can use @app.on_event("startup" | "shutdown")

@app.on_event("startup")
async def startup():
    do something...


@app.on_event("shutdown")
async def shutdown():
    do something...

If you are encountring circular import Error, create your api as router than import from your main file.

Example

from fastapi import APIRouter


router = APIRouter()

@router.on_event("startup")
async def startup():
    do something...

And from your main file

from path_to_your_api import router

app.include_router(router)
Related