What is the repository pattern and how is it implemented in FastAPI?

Answer

The repository pattern abstracts database access behind an interface, keeping route handlers and business logic independent of the database technology. Implementation: class UserRepository: def __init__(self, db: AsyncSession): self.db = db; async def get_by_id(self, user_id: int) -> User | None: result = await self.db.execute(select(User).where(User.id == user_id)); return result.scalar_one_or_none(); async def create(self, data: UserCreate) -> User: user = User(**data.model_dump()); self.db.add(user); await self.db.commit(); await self.db.refresh(user); return user. Create a FastAPI dependency: def get_user_repo(db: AsyncSession = Depends(get_db)) -> UserRepository: return UserRepository(db). Use in route: @app.post('/users') async def create_user(data: UserCreate, repo: UserRepository = Depends(get_user_repo)): return await repo.create(data). Benefits: swap DB without changing routes, mock the repository in tests, keep queries organized per entity.