0
0
FastAPIframework~10 mins

Path parameter types and validation 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 declare a path parameter as an integer in FastAPI.

FastAPI
from fastapi import FastAPI
app = FastAPI()

@app.get('/items/{item_id}')
async def read_item(item_id: [1]):
    return {"item_id": item_id}
Drag options to blanks, or click blank then click option'
Astr
Bbool
Cfloat
Dint
Attempts:
3 left
💡 Hint
Common Mistakes
Using str instead of int for numeric path parameters.
Forgetting to specify a type, which defaults to str.
2fill in blank
medium

Complete the code to validate that the path parameter item_id is greater than zero.

FastAPI
from fastapi import FastAPI, Path
app = FastAPI()

@app.get('/items/{item_id}')
async def read_item(item_id: int = Path(..., gt=[1])):
    return {"item_id": item_id}
Drag options to blanks, or click blank then click option'
A1
B-1
C0
DNone
Attempts:
3 left
💡 Hint
Common Mistakes
Using ge=0 which allows zero, not strictly greater.
Setting gt to a negative number.
3fill in blank
hard

Fix the error in the code by specifying the correct type for the path parameter user_id.

FastAPI
from fastapi import FastAPI
app = FastAPI()

@app.get('/users/{user_id}')
async def get_user(user_id: [1]):
    return {"user_id": user_id}
Drag options to blanks, or click blank then click option'
Afloat
Bint
Cstr
Dbool
Attempts:
3 left
💡 Hint
Common Mistakes
Using str when numeric IDs are expected.
Using float which is not typical for IDs.
4fill in blank
hard

Fill both blanks to declare a path parameter item_id as an integer and validate it to be between 1 and 100.

FastAPI
from fastapi import FastAPI, Path
app = FastAPI()

@app.get('/items/{item_id}')
async def read_item(item_id: [1] = Path(..., ge=[2], le=100)):
    return {"item_id": item_id}
Drag options to blanks, or click blank then click option'
Aint
Bstr
C1
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Using str instead of int.
Setting ge to 0 instead of 1.
5fill in blank
hard

Fill all three blanks to declare a path parameter user_id as an integer, validate it to be positive, and add a description.

FastAPI
from fastapi import FastAPI, Path
app = FastAPI()

@app.get('/users/{user_id}')
async def get_user(user_id: [1] = Path(..., gt=[2], description=[3])):
    return {"user_id": user_id}
Drag options to blanks, or click blank then click option'
Astr
B0
C"The ID of the user"
Dint
Attempts:
3 left
💡 Hint
Common Mistakes
Using str instead of int.
Omitting the description or using wrong quotes.