What is the purpose of a prefix in a FastAPI router?
The prefix adds a common path to all routes in the router, so you don't have to repeat it for each route. It helps organize routes under a shared URL segment.
Click to reveal answer
beginner
How do tags help when using routers in FastAPI?
tags group routes in the automatic API docs, making it easier to find and understand related endpoints.
Click to reveal answer
beginner
Show an example of creating a FastAPI router with a prefix /items and tag Items.
5. You want to create two routers in FastAPI: one for /products tagged 'products' and another for /orders tagged 'orders'. How do you correctly set prefixes and tags to keep your API organized?
hard
A. router_products = APIRouter(prefix='/products', tags=['products'])\nrouter_orders = APIRouter(prefix='/orders', tags=['orders'])
B. router_products = APIRouter(prefix=['products'], tags='products')\nrouter_orders = APIRouter(prefix=['orders'], tags='orders')
C. router_products = APIRouter(prefix='/products', tags='products')\nrouter_orders = APIRouter(prefix='/orders', tags='orders')
D. router_products = APIRouter(tags=['products'])\nrouter_orders = APIRouter(prefix='/orders')
Solution
Step 1: Recall correct types for prefix and tags
Prefix must be a string starting with '/', tags must be a list of strings.
Step 2: Evaluate each option for correctness and organization
router_products = APIRouter(prefix='/products', tags=['products'])\nrouter_orders = APIRouter(prefix='/orders', tags=['orders']) correctly assigns string prefixes and list tags for both routers, organizing API paths and documentation clearly.