Path parameters are values passed directly inside the URL. They are useful for identifying a specific resource.
For example, if you want to get a specific user, you can include the user’s ID directly in the URL:
/users/10
Here, 10 is the path parameter.
Code
from fastapi import FastAPI
app = FastAPI()
@app.get("/users/{user_id}")
def get_user(user_id: int):
return {
"user_id": user_id
}
Understanding the Code
The route contains {user_id}:
@app.get("/users/{user_id}")
This tells FastAPI that user_id is a path parameter.
The function receives the parameter:
def get_user(user_id: int):
The int type indicates that user_id should be an integer.
FastAPI automatically converts and validates the value according to the declared type.
Example Request
You can access the endpoint using:
GET /users/10
Here:
user_id = 10
Output
{
"user_id": 10
}
Summary
Path parameters allow you to pass values directly in the URL.
For example:
/users/10
/users/25
/users/100
In this example, the number in the URL is passed to the user_id parameter:
@app.get("/users/{user_id}")
def get_user(user_id: int):
return {
"user_id": user_id
}