question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Dependency defined on startup event

See original GitHub issue

First Check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn’t find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google “How to X in FastAPI” and didn’t find any information.
  • I already read and followed all the tutorial in the docs and didn’t find an answer.
  • I already checked if it is not related to FastAPI but to Pydantic.
  • I already checked if it is not related to FastAPI but to Swagger UI.
  • I already checked if it is not related to FastAPI but to ReDoc.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

@app.on_event("startup")
async def startup_event():
    something = await func()
    myobj = MyObj(something)

###

@router.get("")
async def index():
  # need myobj instance here

Description

I need to execute some async initialization on startup creating an instance of myobj, and then I need this instance as a dependency in routers endpoint.

Operating System

Windows

Operating System Details

No response

FastAPI Version

0.68.1

Python Version

3.8.8

Additional Context

I need to create an instance of a “master” object asynchronously during the startup of FastApi, and then to get this exact instance in routers endpoint, but I cannot figure out how to pass it as a dependency.

(I’m aware that if I have multiple workers each worker will get a different “master” object but that is ok, the main point here is that within a single worker an instance is created after async operation on startup, and then reused in routers endpoint.)

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:8 (2 by maintainers)

github_iconTop GitHub Comments

3reactions
adriangbcommented, Oct 13, 2021

Another alternative is to store it in the app state:

from fastapi import FastAPI, Depends, Request


class MyObj:
    def __init__(self, something: int) -> None:
        self.something = something


async def on_startup() -> None:
    app.state.myobj = MyObj(1)


app = FastAPI(on_startup=[on_startup])


def get_myobj(request: Request) -> MyObj:
    return request.app.state.myobj


@app.get("/")
async def index(myobj: MyObj = Depends(get_myobj)) -> None:
    assert isinstance(myobj, MyObj)
    assert myobj.something == 1


from fastapi.testclient import TestClient


with TestClient(app) as client:
    resp = client.get("/")
    assert resp.status_code == 200

Or, more in line with traditional dependency injection if you imagine that dependency_overrides is a “container”:

from fastapi import FastAPI, Depends


class MyObj:
    def __init__(self, something: int) -> None:
        self.something = something


async def on_startup() -> None:
    myobj = MyObj(1)
    app.dependency_overrides[MyObj] = lambda: myobj


app = FastAPI(on_startup=[on_startup])


@app.get("/")
async def index(myobj: MyObj = Depends()) -> None:
    assert isinstance(myobj, MyObj)
    assert myobj.something == 1


from fastapi.testclient import TestClient


with TestClient(app) as client:
    resp = client.get("/")
    assert resp.status_code == 200

If this was a more realistic situation, I’d hope this looked like:

from fastapi import FastAPI, Depends


class MyObj:
    def __init__(self, something: int) -> None:
        self.something = something


async def on_startup(container: Container) -> None:
    # get the container or app injected, no need for a reference
    container.bind(MyObj, value=MyObj(1))   # or something like this


app = FastAPI(on_startup=[on_startup])


@app.get("/")
async def index(myobj: MyObj = Depends()) -> None:
    ...
1reaction
desilinguistcommented, Sep 17, 2022

@adriangb thank you so much for the idea about using dependency overrides. It really helped me out!

Read more comments on GitHub >

github_iconTop Results From Across the Web

What is a Dependency? Dependency Definition and Examples
A dependency describes the relationship among activities and specifies the particular order in which they need to be performed.
Read more >
Events: startup - shutdown - FastAPI
You can define event handlers (functions) that need to be executed before the application starts up, or when the application is shutting down....
Read more >
Dependency injection in ASP.NET Core | Microsoft Learn
Learn how ASP.NET Core implements dependency injection and how to use it.
Read more >
What is a Task Dependency? Definition, Types, and Examples
A task dependency is a relationship that requires a particular order for tasks to be performed. It means that one preceding task relies...
Read more >
Everything You Need to Know About Task Dependencies
External: this describes an input from an external source that is required before a task can proceed. These set dependencies frequently take the ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found