0
0
FastAPIframework~10 mins

Including routers in main app in FastAPI - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Including routers in main app
Define Router
Add Routes to Router
Create Main FastAPI App
Include Router in Main App
Run App and Handle Requests
This flow shows how you define a router, add routes to it, create the main app, include the router, and then run the app to handle requests.
Execution Sample
FastAPI
from fastapi import FastAPI, APIRouter

router = APIRouter()

@router.get('/hello')
async def say_hello():
    return {'message': 'Hello from router!'}

app = FastAPI()
app.include_router(router, prefix='/api')
This code creates a router with one GET route, then includes it in the main FastAPI app under the '/api' prefix.
Execution Table
StepActionObject Created/ModifiedEffect
1Import FastAPI and APIRouterModules importedReady to use FastAPI and router classes
2Create APIRouter instancerouterRouter object created to hold routes
3Define GET route '/hello' on routerrouter with routeRoute '/hello' added to router
4Create FastAPI app instanceappMain app object created
5Include router in app with prefix '/api'app with routerRouter routes accessible under '/api' prefix
6Run app and receive GET request to '/api/hello'Request handledReturns JSON {'message': 'Hello from router!'}
7Request to '/hello' (without prefix)No route found404 Not Found error
8Request to '/api/unknown'No route found404 Not Found error
💡 Execution stops after handling requests or when no matching route is found.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4After Step 5Final
routerNoneAPIRouter instanceAPIRouter with '/hello' routeAPIRouter with '/hello' routeSameSame
appNoneNoneNoneFastAPI instanceFastAPI instance with router includedSame
Key Moments - 3 Insights
Why does the route '/hello' not work directly on the main app?
Because the route is defined on the router and included with the prefix '/api', the full path becomes '/api/hello'. Requests to '/hello' do not match any route as shown in execution_table row 7.
What happens if you include the router without a prefix?
The router's routes become available at their original paths. For example, '/hello' would work directly. This is implied by the prefix usage in step 5 and the 404 in step 7.
Can you include multiple routers in the main app?
Yes, you can create multiple APIRouter instances and include each with different prefixes or none. This modularizes your app routes.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'router' after step 3?
AAn APIRouter instance with the '/hello' route added
BNone
CA FastAPI app instance
DAn empty APIRouter instance
💡 Hint
Check the 'router' variable in variable_tracker after step 3 and execution_table row 3.
At which step does the main app include the router?
AStep 2
BStep 5
CStep 4
DStep 6
💡 Hint
Look for the action 'Include router in app' in execution_table.
If you remove the prefix '/api' when including the router, what changes in the execution?
AThe router is not included at all
BThe route '/api/hello' still works
CThe route '/hello' is accessible directly on the main app
DThe app crashes
💡 Hint
Refer to key_moments about prefix usage and execution_table rows 6 and 7.
Concept Snapshot
Define APIRouter and add routes to it
Create FastAPI app instance
Include router in app with app.include_router(router, prefix)
Routes on router are accessed with prefix + route path
Without prefix, routes are at root paths
Use routers to organize app routes modularly
Full Transcript
This example shows how to organize FastAPI routes using routers. First, you import FastAPI and APIRouter. Then, create a router instance and add routes to it, like a GET route at '/hello'. Next, create the main FastAPI app instance. Include the router in the main app using app.include_router(router, prefix='/api'). This means the router's routes are accessed under the '/api' path, so '/api/hello' works but '/hello' does not. When the app runs, requests to '/api/hello' return the expected JSON message. Requests to paths not defined return 404 errors. Using routers helps keep your app organized by grouping related routes and optionally adding prefixes.