When building APIs with FastAPI, you'll often need to handle various types of input data. Two common methods for receiving data in your API endpoints are query parameters and request bodies. In this article, we'll explore both of these concepts and learn how to implement them effectively in your FastAPI applications.
Query parameters are a way to pass data to your API endpoint through the URL. They appear after the question mark (?) in the URL and are separated by ampersands (&).
Let's start with a simple example:
from fastapi import FastAPI app = FastAPI() @app.get("/items") async def read_items(skip: int = 0, limit: int = 10): return {"skip": skip, "limit": limit}
In this example, we've defined two query parameters: skip
and limit
. Users can now call our API like this:
/items?skip=20&limit=50
FastAPI automatically validates and converts the parameters to the specified types (in this case, integers).
Query parameters are optional by default. If you want to make a parameter required, you can use Python's type hints:
@app.get("/items") async def read_items(item_id: int): return {"item_id": item_id}
Now, calling the endpoint without providing item_id
will result in an error.
You can also accept multiple values for a single parameter using Python's list type hint:
from typing import List @app.get("/items") async def read_items(item_ids: List[int] = Query(None)): return {"item_ids": item_ids}
This allows users to call the API like this:
/items?item_ids=1&item_ids=2&item_ids=3
While query parameters are great for simple data, request bodies are better suited for sending larger amounts of structured data to your API.
Here's a simple example of how to use a request body:
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str description: str = None price: float tax: float = None @app.post("/items") async def create_item(item: Item): return item
In this example, we've defined a Pydantic model Item
to represent the structure of our request body. FastAPI will automatically validate the incoming JSON data against this model.
You can use both query parameters and request bodies in the same endpoint:
@app.post("/items/{item_id}") async def update_item(item_id: int, item: Item, q: str = None): result = {"item_id": item_id, **item.dict()} if q: result.update({"q": q}) return result
This endpoint accepts an item_id
as a path parameter, an Item
object in the request body, and an optional query parameter q
.
You can create more complex request bodies using nested Pydantic models:
from pydantic import BaseModel class Image(BaseModel): url: str name: str class Item(BaseModel): name: str description: str = None price: float tax: float = None images: List[Image] = None @app.post("/items") async def create_item(item: Item): return item
You can also accept arrays in your request body:
@app.post("/items") async def create_items(items: List[Item]): return items
This endpoint accepts a JSON array of Item
objects.
By understanding and implementing query parameters and request bodies effectively, you'll be well on your way to creating robust and flexible APIs with FastAPI. Remember to practice and experiment with different scenarios to solidify your understanding of these concepts.
22/11/2024 | Python
21/09/2024 | Python
15/10/2024 | Python
05/10/2024 | Python
08/11/2024 | Python
05/11/2024 | Python
06/10/2024 | Python
25/09/2024 | Python
06/10/2024 | Python
05/10/2024 | Python
26/10/2024 | Python