Hello everyone! I've recently started playing with fastAPI and I have noticed that in all examples I've seen so far that a db session is injected directly into routes/controllers. My question is: why would it be better to do it like this:

def get_users(db: Session, skip: int = 0, limit: int = 100): return db.query(models.User).offset(skip).limit(limit).all() @app.get("/users/", response_model=list[schemas.User]) def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): users = crud.get_users(db, skip=skip, limit=limit) return users

and not creating a UserRepository class or module, that manages its own sessions, thus having no db dependecy whatsoever inside the routes? I've implemented this UserRepository like this:

class UserRepository: def __init__(self, session_factory: sessionmaker): self.session_factory = session_factory self.entity = UserEntity def find_by_id(self, user_id) -> UserEntity: with self.session_factory() as session: return session.query(self.entity).filter(self.entity.id == user_id).first() def add(self, new_user: UserEntity): with self.session_factory() as session: session.add(new_user) session.commit()

Then I am using it in this way:

@router.get("/{id_}", response_model=dto.UserResponseDto) def get_user(id_: int): user = UserRepository(session_factory).find_by_id(id_) if not user: raise HTTPException(status_code=HTTPStatus.NOT_FOUND, detail=f"User with id {id_} was not found") return user

For now the UserRepository still appears in routes, I can make a singleton of it and instantiate it just once in the user_repo module, then import it everywhere. Maybe make a business layer to hide db logic completely.

What are the advantages of using Depends(get_db) inside the route instead of using with self.session_factory() as session as I have done above?

I am coming from Spring Boot/Laravel background, so for me it is a big counterintuitive to have any kind of database dependency inside routers.

Stock Quotes for Bridgeport

Weather Forecast for Bridgeport

Latest News