Bird
Raised Fist0
FastAPIframework~20 mins

Including routers in main app in FastAPI - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Router Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output when accessing /items/42?

Given this FastAPI app with a router included, what will be the JSON response when you visit /items/42?

FastAPI
from fastapi import FastAPI, APIRouter

app = FastAPI()

items_router = APIRouter()

@items_router.get('/items/{item_id}')
async def read_item(item_id: int):
    return {"item_id": item_id, "name": f"Item {item_id}"}

app.include_router(items_router)
A404 Not Found error
B{"detail": "Not Found"}
C{"item_id": 42, "name": "Item 42"}
D{"item_id": "42", "name": "Item 42"}
Attempts:
2 left
💡 Hint

Check how the router path and parameter types match the request URL.

📝 Syntax
intermediate
2:00remaining
Which option correctly includes a router with prefix '/users'?

Choose the correct way to include a router named users_router in the main FastAPI app with the prefix /users.

FastAPI
from fastapi import FastAPI, APIRouter

app = FastAPI()
users_router = APIRouter()

# Assume users_router has some routes defined

# Which line correctly includes the router with prefix '/users'?
Aapp.include(users_router, prefix='/users')
Bapp.include_router(users_router, prefix='/users')
Capp.add_router(users_router, prefix='/users')
Dapp.include_router(users_router, path='/users')
Attempts:
2 left
💡 Hint

Check the FastAPI method name and parameter for adding routers with prefixes.

🔧 Debug
advanced
2:00remaining
Why does this router path not respond as expected?

Consider this router code included in the main app. Why does accessing /api/data return 404?

FastAPI
from fastapi import FastAPI, APIRouter

app = FastAPI()

api_router = APIRouter(prefix='/api')

@api_router.get('/data')
async def get_data():
    return {"data": "value"}

app.include_router(api_router, prefix='/api')
AThe route path becomes '/api/api/data' due to double prefix, so '/api/data' is not found.
BThe router prefix is ignored, so '/data' is the actual path.
CThe function get_data is missing async keyword causing runtime error.
DThe app.include_router call is missing parentheses.
Attempts:
2 left
💡 Hint

Check how prefixes combine when including routers.

❓ state_output
advanced
2:00remaining
What is the response after calling /counter twice?

Given this FastAPI app with a router that keeps a counter, what JSON response do you get on the second call to /counter?

FastAPI
from fastapi import FastAPI, APIRouter

app = FastAPI()
counter_router = APIRouter()

count = 0

@counter_router.get('/counter')
async def get_counter():
    global count
    count += 1
    return {"count": count}

app.include_router(counter_router)
A{"count": 0}
B{"count": 1}
C500 Internal Server Error due to global variable
D{"count": 2}
Attempts:
2 left
💡 Hint

Think about how the global variable changes with each request.

🧠 Conceptual
expert
2:00remaining
What error occurs if you include the same router twice without a prefix?

What happens if you include the same APIRouter instance twice in a FastAPI app without using different prefixes?

FastAPI
from fastapi import FastAPI, APIRouter

app = FastAPI()

router = APIRouter()

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

app.include_router(router)
app.include_router(router)
ARuntimeError: Duplicate route path '/hello' detected
BThe second include_router call is ignored silently
CThe app runs but only one route is registered
DSyntaxError due to duplicate function definitions
Attempts:
2 left
💡 Hint

Think about route conflicts when including routers multiple times.

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