Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dependency injection of crud items #606

Open
SarloAkrobata opened this issue Feb 24, 2024 · 1 comment
Open

Dependency injection of crud items #606

SarloAkrobata opened this issue Feb 24, 2024 · 1 comment

Comments

@SarloAkrobata
Copy link

SarloAkrobata commented Feb 24, 2024

from typing import Any, List

from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session

from app import crud, models, schemas
from app.api import deps

router = APIRouter()



@router.post("/", response_model=schemas.Item)
def create_item(
    *,
    db: Session = Depends(deps.get_db),
    item_in: schemas.ItemCreate,
    current_user: models.User = Depends(deps.get_current_active_user),
) -> Any:
    """
    Create new item.
    """
    item = crud.item.create_with_owner(db=db, obj_in=item_in, owner_id=current_user.id)
    return item


Hi all, why in this and similiar examples crud.item(or user) not injected as dependency?

@bereydev
Copy link

Hey @SarloAkrobata,

crud.item and crud.user or any other functions are not injected as dependencies because they are static functions or variables used directly in the code of the route. FastAPI’s dependency injection is meant for dynamic values like db or current_user that change per request.

Basically if your value depends (that's the keyword here 😉) on the request content and can change or has to be regenerated per request you can use a dependency. If your function, variable or constant is the same for any request then it does not make sens to be a dependency and can be used directly in the body of your route.

I invite your to take a second look at the documentation about dependencies:
https://fastapi.tiangolo.com/tutorial/dependencies/

Hope it helps!

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

No branches or pull requests

2 participants