Shared dependencies across routers in FastAPI
📖 Scenario: You are building a web API for a simple book store. You want to organize your API into separate routers for books and authors. Both routers need to check a shared dependency that simulates user authentication.
🎯 Goal: Create two routers, books_router and authors_router, each with one route. Add a shared dependency get_current_user to both routers so that the user is authenticated before accessing any route.
📋 What You'll Learn
Create a dependency function called
get_current_user that returns a string 'user123'.Create a FastAPI app instance called
app.Create two routers:
books_router and authors_router.Add the
get_current_user dependency to both routers using the dependencies parameter.Add one route
/books/ to books_router that returns a JSON with key 'message' and value 'Books list'.Add one route
/authors/ to authors_router that returns a JSON with key 'message' and value 'Authors list'.Include both routers in the main
app with prefixes /books and /authors respectively.💡 Why This Matters
🌍 Real World
In real web APIs, shared dependencies like authentication or database sessions are used across multiple routers to keep code clean and secure.
💼 Career
Understanding how to share dependencies across routers is essential for building scalable and maintainable FastAPI applications in professional backend development.
Progress0 / 4 steps