📖 Scenario: You are building a simple web API for a bookstore. You want to organize your routes by grouping book-related routes separately from author-related routes.
🎯 Goal: Create a FastAPI app that uses APIRouter to modularize routes for books and authors, then include these routers in the main app.
📋 What You'll Learn
Create a FastAPI app instance named app
Create two APIRouter instances named book_router and author_router
Add a GET route /books/ to book_router that returns a list of book titles
Add a GET route /authors/ to author_router that returns a list of author names
Include both routers in the main app with prefixes /books and /authors respectively
💡 Why This Matters
🌍 Real World
Modular routes help organize large APIs by grouping related endpoints, making code easier to read and maintain.
💼 Career
Using APIRouter is a common practice in professional FastAPI projects to build scalable and clean APIs.
Progress0 / 4 steps
1
Create the FastAPI app and routers
Import FastAPI and APIRouter from fastapi. Create a FastAPI app instance called app. Create two APIRouter instances called book_router and author_router.
FastAPI
Hint
Use app = FastAPI() to create the main app. Use book_router = APIRouter() and author_router = APIRouter() to create routers.
2
Add a GET route to book_router
Add a GET route / to book_router using the decorator @book_router.get("/"). Define a function get_books that returns the list ["The Hobbit", "1984", "Pride and Prejudice"].
FastAPI
Hint
Use @book_router.get("/") above a function named get_books that returns the list of book titles.
3
Add a GET route to author_router
Add a GET route / to author_router using the decorator @author_router.get("/"). Define a function get_authors that returns the list ["J.R.R. Tolkien", "George Orwell", "Jane Austen"].
FastAPI
Hint
Use @author_router.get("/") above a function named get_authors that returns the list of author names.
4
Include routers in the main app
Include book_router in app with prefix /books using app.include_router(book_router, prefix="/books"). Include author_router in app with prefix /authors using app.include_router(author_router, prefix="/authors").
FastAPI
Hint
Use app.include_router() to add both routers with their prefixes.
Practice
(1/5)
1. What is the main purpose of using APIRouter in a FastAPI application?
easy
A. To replace the main FastAPI app instance
B. To handle background tasks
C. To automatically generate database models
D. To organize routes into smaller, manageable groups
Solution
Step 1: Understand APIRouter's role
APIRouter is designed to group related routes together for better organization.
Step 2: Compare with other options
It does not replace the main app, generate models, or handle background tasks.
Final Answer:
To organize routes into smaller, manageable groups -> Option D
Quick Check:
APIRouter groups routes = B [OK]
Hint: APIRouter groups routes for cleaner code [OK]
Common Mistakes:
Thinking APIRouter replaces FastAPI app
Confusing APIRouter with database tools
Assuming APIRouter handles tasks beyond routing
2. Which of the following is the correct way to include a router with a prefix in a FastAPI app?
easy
A. app.include_router(router, prefix='/items')
B. app.add_router(router, prefix='/items')
C. app.include_router(router, path='/items')
D. app.register_router(router, prefix='/items')
Solution
Step 1: Recall the method to add routers
The correct method is include_router() with a prefix argument.
Step 2: Check method names and parameters
Only include_router() with prefix is valid; others are incorrect method names or parameters.
Final Answer:
app.include_router(router, prefix='/items') -> Option A
Quick Check:
Use include_router with prefix = A [OK]
Hint: Use include_router() with prefix to add routes [OK]
Common Mistakes:
Using wrong method names like add_router or register_router
Using 'path' instead of 'prefix' argument
Forgetting to include the router at all
3. Given this code snippet, what will be the URL path to access the read_users endpoint?
A. The prefix causes route conflict with root app route
B. APIRouter cannot be included with prefix
C. Router path must start with '/api'
D. The router function must be synchronous
Solution
Step 1: Analyze route paths
The router has a route at /items and is included with prefix /, making its full path /items.
Step 2: Check for conflicts
The main app also has a route at /items. This causes a direct route conflict.
Step 3: Identify the actual problem
The prefix causes the router path to overlap with the root app route.
Final Answer:
The prefix causes route conflict with root app route -> Option A
Quick Check:
Prefix and root route clash = A [OK]
Hint: Avoid prefix same as root route path [OK]
Common Mistakes:
Thinking APIRouter can't use prefix
Assuming router paths must start with /api
Believing async functions must be sync
5. You want to create two routers: one for user routes with prefix /users and one for item routes with prefix /items. How should you include them in your FastAPI app to avoid route conflicts and keep code modular?
hard
A. Define all routes directly in the main FastAPI app without routers
B. Create two APIRouter instances, define routes, then include both with their prefixes in the main app
C. Create one APIRouter with all routes and include it without prefixes
D. Use one APIRouter and change prefixes dynamically inside route functions
Solution
Step 1: Understand modular routing
Using separate APIRouter instances for users and items keeps routes organized and modular.
Step 2: Include routers with distinct prefixes
Including each router with its own prefix (/users and /items) avoids conflicts and clarifies URLs.
Step 3: Avoid other options
Single router or no routers reduce modularity; dynamic prefix changes are not standard practice.
Final Answer:
Create two APIRouter instances, define routes, then include both with their prefixes in the main app -> Option B
Quick Check:
Separate routers + prefixes = modular, no conflicts [OK]
Hint: Use separate routers with prefixes for modularity [OK]
Common Mistakes:
Putting all routes in one router without prefixes
Defining routes only in main app losing modularity
Trying to change prefixes inside route functions
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.