0
0
FastAPIframework~30 mins

Including routers in main app in FastAPI - Mini Project: Build & Apply

Choose your learning style9 modes available
Including routers in main app
📖 Scenario: You are building a simple web API using FastAPI. To keep your code organized, you want to separate different parts of your API into routers. Routers help you group related routes together, like having different rooms for different activities in a house.
🎯 Goal: Build a FastAPI app that includes a router from another module. The router will have one route that returns a greeting message. You will create the router, then include it in the main app.
📋 What You'll Learn
Create a router in a separate module called items.py.
The router should have a GET route at / that returns a JSON message.
In the main app file main.py, create a FastAPI app instance.
Include the router from items.py into the main app with the prefix /items.
💡 Why This Matters
🌍 Real World
Organizing routes into routers helps keep large FastAPI projects clean and maintainable, similar to organizing files in folders.
💼 Career
Knowing how to modularize FastAPI apps with routers is essential for backend developers building scalable APIs.
Progress0 / 4 steps
1
Create a router in items.py
In a file named items.py, import APIRouter from fastapi. Then create a router called router using APIRouter(). Add a GET route at / on router that returns a dictionary with the key message and value "Hello from items router".
FastAPI
Need a hint?

Remember to import APIRouter and create a router instance. Use @router.get("/") to define the route.

2
Create the main FastAPI app in main.py
In main.py, import FastAPI from fastapi. Create an app instance called app using FastAPI().
FastAPI
Need a hint?

Import FastAPI and create an app instance named app.

3
Import the router from items.py
In main.py, import the router from the items module.
FastAPI
Need a hint?

Use from items import router to bring the router into main.py.

4
Include the router in the main app with prefix
In main.py, use app.include_router() to add the imported router to the app. Use the prefix "/items" so the router's routes start with /items.
FastAPI
Need a hint?

Call app.include_router(router, prefix="/items") to add the router under the /items path.