What is FastAPI's dependency injection system?

Answer

FastAPI has a built-in dependency injection system using the Depends() function. Dependencies are callable functions that are called automatically and their return values are injected into route handlers. Example: def get_db(): db = Session(); try: yield db; finally: db.close(). Use in a route: @app.get('/users') async def get_users(db: Session = Depends(get_db)): return db.query(User).all(). FastAPI calls get_db() before the handler, injects the session, and runs the cleanup after. Dependencies can depend on other dependencies (chaining). Common uses: database sessions, authentication (extract and verify JWT, inject current user), config injection, and shared request parsing. Dependencies can also be classes with a __call__ method. This system makes route handlers clean and testable.