Python
Path parameter
Learn path parameters with /items/{id}.
Path parameter
A placeholder of the form {name} in the path becomes a path parameter. The function parameter with the same name matches it; FastAPI extracts the value from the URL and passes it.
@app.get("/items/{item_id}")
def read_item(item_id: int):
return {"item_id": item_id}
With the type int, FastAPI converts automatically. If the value does not match, a 422 response is returned. This is ideal for routes that take a resource id.
Type conversion
You can give path parameters types like int, str, float. FastAPI converts the string from the URL to this type; if it cannot, a 422 response is returned.
@app.get("/items/{item_id}")
def read_item(item_id: int):
# item_id is an int here
return {"item_id": item_id, "tipi": type(item_id).__name__}
Without a type, the parameter is treated as str. Giving a type strengthens validation and documentation.
Exercise GET route with a path parameter
Start with from fastapi import FastAPI and from fastapi.testclient import TestClient. Define app = FastAPI(). With @app.get("/items/{item_id}") define def read_item(item_id: int): returning {"item_id": item_id}. Create a client with client = TestClient(app). Print the response body with print(client.get("/items/5").text).
Show example solution
from fastapi import FastAPI
from fastapi.testclient import TestClient
app = FastAPI()
@app.get("/items/{item_id}")
def read_item(item_id: int):
return {"item_id": item_id}
client = TestClient(app)
print(client.get("/items/5").text)
Test yourself
-
How is item_id obtained in @app.get("/items/{item_id}")?
- Through the function parameter
- Through a global variable
- From the query string
- By reading from a file
Show answer
Through the function parameter — item_id is obtained through the function parameter with the same name.
-
Complete the path parameter route
@app.get("/items/____")
def read_item(item_id: int):
Show answer
@app.get("/items/{item_id}")
def read_item(item_id: int):
-
Match the path parameter concepts
- {item_id}
- Is the placeholder
- item_id: int
- Is a type conversion
- 422
- Is a validation error
- /items/{id}
- Is a path template
Next lesson: Query parameter