FastAPI Handling Request Data


How does FastAPI handle request data?

FastAPI handles request data by allowing you to define the expected structure of the incoming data using Python type hints and Pydantic models. FastAPI can handle data sent via path parameters, query parameters, form data, request bodies, and file uploads. It automatically validates and parses the incoming data based on the types defined in the route function.


How do you handle path parameters in FastAPI?

Path parameters are values included in the URL path and are mandatory. FastAPI automatically extracts and validates path parameters based on the type annotations you provide in the route function.

Example of handling path parameters:

from fastapi import FastAPI

app = FastAPI()

@app.get("/items/{item_id}")
def read_item(item_id: int):
    return {"item_id": item_id}

In this example, the item_id is a path parameter, and FastAPI automatically parses and validates it as an integer from the URL path.


How do you handle query parameters in FastAPI?

Query parameters are optional key-value pairs included in the URL after the ? symbol. You can define query parameters in the route function, and FastAPI will automatically validate and parse them.

Example of handling query parameters:

@app.get("/items/")
def read_items(skip: int = 0, limit: int = 10):
    return {"skip": skip, "limit": limit}

In this example, skip and limit are optional query parameters. If they are not provided in the request, FastAPI uses the default values (0 and 10, respectively).


How do you handle request bodies in FastAPI?

Request bodies in FastAPI are used to send data like JSON or form data in POST, PUT, and PATCH requests. FastAPI uses Pydantic models to validate and parse the request body data, ensuring that it conforms to the expected types and structure.

Example of handling request bodies:

from pydantic import BaseModel

class Item(BaseModel):
    name: str
    price: float

@app.post("/items/")
def create_item(item: Item):
    return item

In this example, the Item model defines the structure of the request body. FastAPI automatically validates the incoming JSON request body to ensure it has a name (string) and a price (float).


How do you handle form data in FastAPI?

FastAPI can handle form data submitted from HTML forms using the Form class. This is useful when building traditional web forms that use the application/x-www-form-urlencoded or multipart/form-data encoding.

Example of handling form data:

from fastapi import FastAPI, Form

@app.post("/login/")
def login(username: str = Form(...), password: str = Form(...)):
    return {"username": username}

In this example, the Form class is used to parse form data submitted via an HTML form. The username and password fields are extracted from the form submission.


How do you handle file uploads in FastAPI?

FastAPI allows you to handle file uploads using the File class. It can handle both single and multiple file uploads in multipart/form-data requests.

Example of handling file uploads:

from fastapi import FastAPI, File, UploadFile

@app.post("/upload/")
def upload_file(file: UploadFile = File(...)):
    return {"filename": file.filename}

In this example, UploadFile is used to handle the file upload, and FastAPI parses the file from the request. The filename of the uploaded file is returned in the response.


How do you handle multiple file uploads in FastAPI?

FastAPI can handle multiple file uploads by accepting a list of UploadFile objects. This allows users to upload several files in one request.

Example of handling multiple file uploads:

from typing import List
from fastapi import FastAPI, File, UploadFile

@app.post("/uploadfiles/")
def upload_files(files: List[UploadFile] = File(...)):
    return {"filenames": [file.filename for file in files]}

In this example, the route /uploadfiles/ accepts multiple files as a list of UploadFile objects, and FastAPI parses them from the request.


How do you handle request headers in FastAPI?

FastAPI allows you to access and validate request headers using the Header class. You can specify which headers are required or optional, and FastAPI will automatically parse and validate them.

Example of handling request headers:

from fastapi import FastAPI, Header

@app.get("/items/")
def read_items(user_agent: str = Header(None)):
    return {"User-Agent": user_agent}

In this example, the user_agent header is extracted from the request using the Header class. If the header is not present, FastAPI assigns None as the default value.


How do you handle cookies in FastAPI?

FastAPI allows you to extract and validate cookies from incoming requests using the Cookie class. Cookies are typically used to store session data or user information between requests.

Example of handling cookies:

from fastapi import FastAPI, Cookie

@app.get("/items/")
def read_items(session_id: str = Cookie(None)):
    return {"session_id": session_id}

In this example, the session_id cookie is extracted from the request using the Cookie class. If the cookie is not present, FastAPI assigns None as the default value.


How do you handle custom request validation in FastAPI?

FastAPI allows you to implement custom validation logic using Pydantic's validator decorator. This allows you to define custom rules for how incoming data should be validated before it reaches the route handler.

Example of custom request validation:

from pydantic import BaseModel, validator

class Item(BaseModel):
    name: str
    price: float

    @validator('price')
    def price_must_be_positive(cls, v):
        if v <= 0:
            raise ValueError('Price must be positive')
        return v

@app.post("/items/")
def create_item(item: Item):
    return item

In this example, a custom validator ensures that the price field is positive. If the validation fails, FastAPI returns an error response.


How do you handle JSON request bodies in FastAPI?

FastAPI automatically parses JSON request bodies using Pydantic models. You define the expected structure of the JSON data, and FastAPI validates the incoming request body to ensure it matches the model.

Example of handling JSON request bodies:

from pydantic import BaseModel

class Item(BaseModel):
    name: str
    description: str

@app.post("/items/")
def create_item(item: Item):
    return item

In this example, FastAPI expects a JSON request body containing name and description. If the data is invalid or missing fields, FastAPI returns a validation error response.

Ads