Bird
Raised Fist0
FastAPIframework~10 mins

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

Choose your learning style10 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.

Practice

(1/5)
1. What is the main purpose of using include_router in a FastAPI application?
easy
A. To handle user authentication automatically.
B. To automatically generate HTML templates for the app.
C. To connect the app to a database.
D. To split the app into smaller, manageable parts for better organization.

Solution

  1. Step 1: Understand the role of routers in FastAPI

    Routers help organize routes by grouping related endpoints together.
  2. Step 2: Recognize what include_router does

    It adds these grouped routes into the main app, keeping code clean and modular.
  3. Final Answer:

    To split the app into smaller, manageable parts for better organization. -> Option D
  4. Quick Check:

    Router inclusion = app organization [OK]
Hint: Routers help organize routes; include_router adds them to main app [OK]
Common Mistakes:
  • Thinking include_router generates HTML templates
  • Confusing routers with database connections
  • Assuming include_router handles authentication
2. Which of the following is the correct way to include a router named user_router with prefix /users in a FastAPI app named app?
easy
A. app.add_router(user_router, prefix='/users')
B. app.include_router(user_router, prefix='/users')
C. app.include(user_router, prefix='/users')
D. app.router_include(user_router, prefix='/users')

Solution

  1. Step 1: Recall the correct method name for adding routers

    The method is include_router, not add_router or others.
  2. Step 2: Check the syntax for prefix argument

    The prefix is passed as a keyword argument prefix='/users'.
  3. Final Answer:

    app.include_router(user_router, prefix='/users') -> Option B
  4. Quick Check:

    Method name is include_router with prefix argument [OK]
Hint: Use include_router with prefix keyword to add routers [OK]
Common Mistakes:
  • Using wrong method names like add_router
  • Passing prefix as positional argument
  • Misspelling include_router
3. Given this code snippet, what will be the URL path to access the get_items endpoint?
from fastapi import FastAPI, APIRouter

app = FastAPI()
router = APIRouter()

@router.get('/items')
async def get_items():
    return {'items': [1, 2, 3]}

app.include_router(router, prefix='/api')
medium
A. /api/items
B. /items
C. /router/items
D. /api/router/items

Solution

  1. Step 1: Identify the route path in the router

    The endpoint is defined at /items inside the router.
  2. Step 2: Understand the prefix added when including the router

    The router is included with prefix /api, so the full path is /api/items.
  3. Final Answer:

    /api/items -> Option A
  4. Quick Check:

    Router prefix + endpoint path = full URL [OK]
Hint: Full path = prefix + router path [OK]
Common Mistakes:
  • Ignoring the prefix when accessing the endpoint
  • Assuming router name appears in URL
  • Confusing endpoint path with prefix
4. What is wrong with this FastAPI code snippet?
from fastapi import FastAPI, APIRouter

app = FastAPI()
router = APIRouter()

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

app.include_router(router, prefix='/greet')
app.include_router(router, prefix='/greet')
medium
A. Including the same router twice with the same prefix causes duplicate routes.
B. The router must be included before defining endpoints.
C. The prefix argument must be omitted when including routers.
D. The router variable should be named app_router instead of router.

Solution

  1. Step 1: Check how many times the router is included

    The router is included twice with the same prefix /greet.
  2. Step 2: Understand the effect of including the same router twice

    This causes duplicate routes, which can lead to errors or unexpected behavior.
  3. Final Answer:

    Including the same router twice with the same prefix causes duplicate routes. -> Option A
  4. Quick Check:

    Duplicate router inclusion = duplicate routes [OK]
Hint: Avoid including the same router twice with same prefix [OK]
Common Mistakes:
  • Thinking router must be included before endpoints
  • Believing prefix is mandatory or must be omitted
  • Confusing variable naming with functionality
5. You have two routers: user_router with prefix /users and item_router with prefix /items. You want to include both in your FastAPI app and add tags for automatic docs grouping. Which code snippet correctly includes both routers with tags?
hard
A. app.include_router(user_router, prefix='/users', tags='users') app.include_router(item_router, prefix='/items', tags='items')
B. app.include_router(user_router, prefix='/users') app.include_router(item_router, prefix='/items') app.tags = ['users', 'items']
C. app.include_router(user_router, prefix='/users', tags=['users']) app.include_router(item_router, prefix='/items', tags=['items'])
D. app.include_router(user_router, tags=['users']) app.include_router(item_router, tags=['items'])

Solution

  1. Step 1: Check how to add tags when including routers

    Tags are passed as a list to the tags argument in include_router.
  2. Step 2: Verify prefix and tags usage for both routers

    Each router is included with its prefix and tags as lists, e.g., tags=['users'].
  3. Final Answer:

    app.include_router(user_router, prefix='/users', tags=['users']) app.include_router(item_router, prefix='/items', tags=['items']) -> Option C
  4. Quick Check:

    Tags must be lists in include_router calls [OK]
Hint: Pass tags as list when including routers for docs grouping [OK]
Common Mistakes:
  • Passing tags as string instead of list
  • Setting tags on app instead of routers
  • Omitting tags argument entirely
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard