Navigating URLs: Path and Query Parameters
Navigating URLs: Path and Query Parameters
Section titled “Navigating URLs: Path and Query Parameters”Path Parameters
Section titled “Path Parameters”Path parameters are variable parts of a URL path. They are used to identify a specific resource, such as a user ID or an item ID. In FastAPI, you can define them using Python format string syntax {}.
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id}")def read_item(item_id): return {"item_id": item_id}If you go to http://127.0.0.1:8000/items/foo, the application captures foo and passes it to the read_item function as the argument item_id.
Type Declaration and Automatic Conversion
Section titled “Type Declaration and Automatic Conversion”You can declare the type of a path parameter using standard Python type hints. This enables FastAPI to automatically validate and convert the data.
@app.get("/items/{item_id}")def read_item(item_id: int): return {"item_id": item_id}By adding : int, FastAPI gives you several features:
- Data Conversion: If you access
/items/5, FastAPI converts the string “5” to the integer5. - Data Validation: If you access
/items/foo, FastAPI will return a readable error because “foo” is not a valid integer. - Documentation: The API docs will correctly display that
item_idmust be an integer.
Query Parameters
Section titled “Query Parameters”Query parameters are the key-value pairs that appear after the ? in a URL, separated by &. When you declare function parameters that are not part of the path parameters, FastAPI interprets them as query parameters.
@app.get("/items/")def read_items(skip: int = 0, limit: int = 10): return {"skip": skip, "limit": limit}For the URL http://127.0.0.1:8000/items/?skip=0&limit=10, the function receives 0 and 10.
Default Values and Optional Parameters
Section titled “Default Values and Optional Parameters”In the example above, skip has a default value of 0 and limit has a default of 10. This means if the client does not send them in the URL, FastAPI uses these values automatically.
To make a parameter truly optional (where it can be None), you can use Python’s Optional or the modern | syntax (Python 3.10+):
from typing import Union
@app.get("/items/{item_id}")def read_item(item_id: str, q: Union[str, None] = None): # q is optional and defaults to None if q: return {"item_id": item_id, "q": q} return {"item_id": item_id}In this case, q is a query parameter because it is not in the path. Since it has = None, it is not required.