Given this FastAPI app with a router included, what will be the JSON response when you visit /items/42?
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)
Check how the router path and parameter types match the request URL.
The router defines a GET endpoint at /items/{item_id} where item_id is an integer. Accessing /items/42 matches this route and returns the JSON with item_id as 42 and the name formatted accordingly.
Choose the correct way to include a router named users_router in the main FastAPI app with the prefix /users.
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'?
Check the FastAPI method name and parameter for adding routers with prefixes.
The correct method to add a router is include_router and the parameter to add a prefix is prefix. Other options use incorrect method names or parameters.
Consider this router code included in the main app. Why does accessing /api/data return 404?
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')
Check how prefixes combine when including routers.
The router is defined with prefix '/api' and then included with prefix '/api' again. This results in the full path being '/api/api/data'. Accessing '/api/data' returns 404 because it does not match any route.
Given this FastAPI app with a router that keeps a counter, what JSON response do you get on the second call to /counter?
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)
Think about how the global variable changes with each request.
The global variable count starts at 0 and increments by 1 on each call. The first call returns 1, the second call returns 2.
What happens if you include the same APIRouter instance twice in a FastAPI app without using different prefixes?
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)
Think about route conflicts when including routers multiple times.
Including the same router twice without prefixes causes FastAPI to detect duplicate routes with the same path and method, raising a RuntimeError.