0
0
FastAPIframework~30 mins

APIRouter for modular routes in FastAPI - Mini Project: Build & Apply

Choose your learning style9 modes available
APIRouter for modular routes
📖 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
Need a 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
Need a 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
Need a 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
Need a hint?

Use app.include_router() to add both routers with their prefixes.