Implementing HTTP Request Methods and Parameter Handling in FastAPI
FastAPI supports standard RESTful HTTP methods for API design. These methods define operations on resources identified by URIs (Uniform Resource Identifiers).
Common HTTP Methods:
GET: Retrieve data from the server (Read).POST: Submit data to the server (Create).PUT: Update an existing resource (Update/Replace).DELETE: Remove a resource (Delete).PATCH: Apply partial modifications to a resource (Partial Update).
Defining these endpoints in FastAPI innvolves decorating functions with specific HTTP method decorators.
Basic Method Implementation
from fastapi import FastAPI
app = FastAPI()
@app.get("/example")
def handle_get():
return {"operation": "GET request processed"}
@app.post("/example")
def handle_post():
return {"operation": "POST request processed"}
@app.put("/example")
def handle_put():
return {"operation": "PUT request processed"}
@app.patch("/example")
def handle_patch():
return {"operation": "PATCH request processed"}
@app.delete("/example")
def handle_delete():
return {"operation": "DELETE request processed"}
Each endpoint responds to a different HTTP method at the same /example path. A development server can be launched using Uvicorn.
Handling Request Parameters
Client requests oftan include parameters passed via different parts of the HTTP request.
Path Parameters
Path parameters are variable parts of the URL route, typically used to identify a specific resource.
@app.get("/users/{user_id}")
def fetch_user(user_id: int):
return {"user_id": user_id}
Multiple path parameters can be defined:
@app.get("/users/{user_id}/orders/{order_id}")
def get_order(user_id: int, order_id: int):
return {"user_id": user_id, "order_id": order_id}
Query Parameters
Query parameters are optional key-value pairs appended to the URL after a ?, commonly used for filtering, pagination, or sorting.
@app.get("/articles")
def list_articles(limit: int = 10, page: int = 1, search_term: str = None):
return {
"limit": limit,
"page": page,
"search_term": search_term
}
Parameters limit and page have default values. The search_term is optional and defaults to None. A request to /articles?limit=20&page=2&search_term=Python would use these values.
Request Headers
HTTP headers convey metadata about the request, such as authentication tokens or content type.
from fastapi import FastAPI, Header
from typing import Optional
app = FastAPI()
@app.get("/header-info")
def read_headers(
user_agent: Optional[str] = Header(None),
content_type: Optional[str] = Header(None)
):
return {
"User-Agent": user_agent,
"Content-Type": content_type
}
Using Header(None) makes the header parameter optional. To access all headers:
from fastapi import FastAPI, Request
app = FastAPI()
@app.get("/all-headers")
def all_headers(request: Request):
return dict(request.headers)
Request Body Data
For POST and similar methods, data is often sent in the request body. FastAPI uses Pydantic models for type validation and data parsing.
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Product(BaseModel):
name: str
description: str
price: float
tax: float = 0.0 # Optional field with default value
@app.post("/products")
def create_product(item: Product):
return {
"name": item.name,
"description": item.description,
"price": item.price,
"tax": item.tax
}
This defines a Product model where name, description, and price are required, and tax is optional with a default. A POST request with a JSON body matching this structure will be automatically validated and parsed.