0
0
FastAPIframework~10 mins

Route ordering and priority in FastAPI - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define a route that matches the path '/items'.

FastAPI
from fastapi import FastAPI
app = FastAPI()

@app.get("[1]")
def read_items():
    return {"message": "List of items"}
Drag options to blanks, or click blank then click option'
A/items/{item_id}
B/item/{id}
C/items
D/
Attempts:
3 left
💡 Hint
Common Mistakes
Using a path with parameters when the route should be static.
Forgetting the leading slash in the path.
2fill in blank
medium

Complete the code to define a route that matches any item ID as a path parameter.

FastAPI
from fastapi import FastAPI
app = FastAPI()

@app.get("[1]")
def read_item(item_id: int):
    return {"item_id": item_id}
Drag options to blanks, or click blank then click option'
A/items/{item_id}
B/items
C/item/{id}
D/items/{id}
Attempts:
3 left
💡 Hint
Common Mistakes
Using a different parameter name in the path and function.
Omitting the curly braces around the parameter.
3fill in blank
hard

Fix the error in the route order to ensure the static route '/users/me' is matched before the dynamic route.

FastAPI
from fastapi import FastAPI
app = FastAPI()

@app.get("/users/me")
def read_current_user():
    return {"user": "current user"}

@app.get("/users/[1]")
def read_user(user_id: str):
    return {"user_id": user_id}
Drag options to blanks, or click blank then click option'
Ame
B{id}
Ccurrent
D{user_id}
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'me' as a parameter instead of a static path segment.
Defining the dynamic route before the static route.
4fill in blank
hard

Fill both blanks to create a route that matches a file path with an extension and a route that matches a specific file name.

FastAPI
from fastapi import FastAPI
app = FastAPI()

@app.get("/files/[2]")
def read_readme():
    return {"file": "README file"}

@app.get("/files/[1]")
def read_file(file_path: str):
    return {"file_path": file_path}
Drag options to blanks, or click blank then click option'
A{file_path:path}
BREADME.md
C{filename}
DREADME
Attempts:
3 left
💡 Hint
Common Mistakes
Using a simple parameter without ':path' for file paths.
Not matching the exact file name in the static route.
5fill in blank
hard

Fill all three blanks to create a dictionary comprehension that maps route names to their handler functions only if the route name starts with 'get'.

FastAPI
routes = {
    [1]: [2] for [3] in route_list if [3].startswith('get')
}
Drag options to blanks, or click blank then click option'
Aroute_name
Bhandlers[route_name]
Droute
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names inconsistently.
Not filtering routes starting with 'get'.