Skip to content
Discussion options

You must be logged in to vote

Re:

I don't see how this solves anything.

I think the solution looks like this:

router = APIRouter(prefix="/items", tags=["items"])

DBSession = Annotated[Session, Depends(get_db)]

@router.get("/")
async def customers_list(db: DBSession) -> list[Item]:
    return db.do_something()

Two things:

  1. Notice how I skipped dependencies=[Depends(get_db)] from APIRouter and instead declared annotated Session with the dep.
  2. Notice how you don't have to do db: Session = Depends(get_db) on every route handler.

Imo seems counter intuitive, but I think the magic was that Session being Annotated makes FastAPI inject it to the route handler.

Replies: 7 comments 14 replies

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
3 replies
@juliocefe
Comment options

@juliocefe
Comment options

@will-e-yams
Comment options

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
1 reply
@will-e-yams
Comment options

Comment options

You must be logged in to vote
2 replies
@arielnmz
Comment options

Answer selected by YuriiMotov
@will-e-yams

This comment was marked as off-topic.

Comment options

You must be logged in to vote
6 replies
@DJoepie
Comment options

@will-e-yams
Comment options

@n8sty
Comment options

@nfnfgo
Comment options

@fkapsahili
Comment options

Comment options

You must be logged in to vote
2 replies
@will-e-yams
Comment options

@mammothrider
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Question or problem question-migrate
Converted from issue

This discussion was converted from issue #3778 on February 28, 2023 16:37.