In FastAPI, a route is a combination of an HTTP method (GET, POST, PUT, DELETE, etc.) and a path. For example, a GET request to the path /items
might be used to retrieve a list of items. Routes are defined using decorators provided by FastAPI.
Path parameters are variables that are part of the URL path. They are used to pass dynamic values to your API endpoints. For instance, if you want to retrieve a specific item with an ID, you can use a path parameter in the URL like /items/{item_id}
.
Here is a simple example of defining a basic GET route in FastAPI:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
In this example, we define a GET route for the root path (/
). When a client makes a GET request to the root of the application, the read_root
function is called, and it returns a JSON response.
Let’s see how to use path parameters to retrieve a specific item:
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id}")
def read_item(item_id: int):
return {"item_id": item_id}
In this code, we define a GET route with a path parameter item_id
. The type hint int
ensures that the item_id
is converted to an integer. When a client makes a GET request to a path like /items/42
, the read_item
function is called with item_id
set to 42
.
You can have multiple path parameters in a single route. Here is an example:
from fastapi import FastAPI
app = FastAPI()
@app.get("/users/{user_id}/items/{item_id}")
def read_user_item(user_id: int, item_id: int):
return {"user_id": user_id, "item_id": item_id}
The order of routes matters in FastAPI. Routes are checked in the order they are defined. So, if you have a route like /items/all
and another route /items/{item_id}
, you should define the /items/all
route first. Otherwise, the /items/{item_id}
route will match the /items/all
path, treating all
as an item_id
.
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/all")
def read_all_items():
return {"message": "All items"}
@app.get("/items/{item_id}")
def read_item(item_id: int):
return {"item_id": item_id}
Use meaningful names for your paths and path parameters. For example, instead of /p/{id}
, use /products/{product_id}
. This makes your API more understandable and maintainable.
FastAPI uses type hints to validate path parameters. Make sure to use appropriate type hints to ensure that the input is in the correct format. If the input cannot be converted to the specified type, FastAPI will automatically return a 422 Unprocessable Entity error.
Implement proper error handling for path parameters. For example, if you expect a positive integer as a path parameter, you can add custom validation logic to handle invalid input gracefully.
from fastapi import FastAPI, HTTPException
app = FastAPI()
@app.get("/items/{item_id}")
def read_item(item_id: int):
if item_id < 1:
raise HTTPException(status_code=400, detail="Item ID must be a positive integer")
return {"item_id": item_id}
FastAPI path operations provide a powerful and flexible way to define routes and handle path parameters in your API. By understanding the fundamental concepts, usage methods, common practices, and best practices, you can build robust and efficient APIs. The use of type hints for validation and the simplicity of route definition make FastAPI a great choice for developing modern web APIs.