0
0
FastAPIframework~10 mins

Router prefix and tags in FastAPI - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Router prefix and tags
Create APIRouter
Set prefix and tags
Define route functions
Include router in main app
Client sends request
Match prefix + path
Execute route function
Return response with tags metadata
This flow shows how a router with a prefix and tags is created, routes are defined, and requests are matched using the prefix before executing the route.
Execution Sample
FastAPI
from fastapi import FastAPI, APIRouter

router = APIRouter(prefix="/items", tags=["items"])

@router.get("/")
async def read_items():
    return [{"item_id": "foo"}]

app = FastAPI()
app.include_router(router)
Defines a router with prefix '/items' and tag 'items', then includes it in the main FastAPI app.
Execution Table
StepActionPrefixTagsRoute PathRequest URLMatched RouteResponse
1Create APIRouter/items["items"]N/AN/AN/AN/A
2Define route @router.get("/")/items["items"]/N/AN/AN/A
3Include router in app/items["items"]/N/AN/AN/A
4Client sends GET request/items["items"]//items/Yes[{"item_id": "foo"}]
5Client sends GET request/items["items"]//items/123No404 Not Found
6Client sends GET request/items["items"]//other/No404 Not Found
💡 Execution stops after matching request URL with router prefix and route path or returning 404 if no match.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
router.prefixNone/items/items/items/items
router.tagsNone["items"]["items"]["items"]["items"]
route.pathNoneN/A///
app.routers[][][][router][router]
Key Moments - 3 Insights
Why does the route path '/' become '/items/' when accessed?
Because the router has a prefix '/items', all routes inside it are accessed with that prefix added before the route path. See execution_table step 4.
What happens if a request URL does not start with the router prefix?
The router does not match the request, so FastAPI returns a 404 Not Found. See execution_table steps 5 and 6.
How do tags affect the API?
Tags group routes in the automatic API docs for easier navigation. They do not affect routing behavior. This is set when creating the router (step 1).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 4. What is the response when the client requests '/items/'?
A[{"item_id": "foo"}]
B404 Not Found
CEmpty list []
DError: No route
💡 Hint
Check the 'Response' column at step 4 in execution_table.
At which step does the router get included in the main FastAPI app?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at the 'Action' column for including router in app.
If the router prefix was changed to '/products', what would be the matched route for request URL '/items/'?
AMatched route with response [{"item_id": "foo"}]
BNo match, 404 Not Found
CMatched route but empty response
DServer error
💡 Hint
Refer to how prefix affects matching in execution_table steps 4 and 5.
Concept Snapshot
APIRouter(prefix, tags) sets a common path prefix and groups routes.
Routes inside use relative paths.
Include router in FastAPI app to activate.
Requests match prefix + route path.
Tags organize routes in docs, no routing effect.
Full Transcript
This visual execution shows how FastAPI's APIRouter uses prefix and tags. First, a router is created with a prefix '/items' and tags ['items']. Then a route is defined at path '/'. When the router is included in the main app, all routes inside it are accessed with the prefix added, so '/' becomes '/items/'. When a client sends a request to '/items/', the router matches and executes the route function, returning the response. Requests not starting with the prefix do not match and return 404. Tags help organize routes in API docs but do not affect routing. The variable tracker shows how prefix and tags stay constant after setup. Key moments clarify why prefix changes route paths and how unmatched URLs behave. The quiz tests understanding of routing and prefix effects.