0
0
FastAPIframework~30 mins

Shared dependencies across routers in FastAPI - Mini Project: Build & Apply

Choose your learning style9 modes available
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
1
Create the shared dependency function
Create a function called get_current_user that returns the string 'user123'.
FastAPI
Need a hint?

This function simulates user authentication by returning a fixed user ID.

2
Create FastAPI app and routers with shared dependency
Import FastAPI and APIRouter from fastapi. Create a FastAPI app called app. Create two routers called books_router and authors_router with the shared dependency get_current_user added using the dependencies parameter.
FastAPI
Need a hint?

Use Depends(get_current_user) inside the dependencies list when creating each router.

3
Add routes to routers
Add a GET route / to books_router that returns {'message': 'Books list'}. Add a GET route / to authors_router that returns {'message': 'Authors list'}.
FastAPI
Need a hint?

Use the @router.get('/') decorator and define functions that return the required dictionaries.

4
Include routers in the main app
Include books_router in app with prefix /books. Include authors_router in app with prefix /authors.
FastAPI
Need a hint?

Use app.include_router() with the correct router and prefix.