Python > Web Development with Python > Asynchronous Web Frameworks (e.g., FastAPI, AsyncIO) > Request and Response in FastAPI

FastAPI Response Model with Status Code

This example shows how to customize the HTTP status code and response model in FastAPI. We use the `status_code` parameter in the route decorator to set a custom status code and use Pydantic to define the structure of successful and error responses.

Import necessary libraries and define the FastAPI app

We start by importing necessary modules from `fastapi` and `pydantic`. Specifically, `status` is imported from `fastapi` to use predefined HTTP status code constants. We also initialize our FastAPI application.

from typing import Union

from fastapi import FastAPI, status
from pydantic import BaseModel

app = FastAPI()

Define data models for success and error responses

Here, we define two Pydantic models: `Item` to represent a successful response containing item details, and `Message` to represent an error response. `Item` contains typical fields like `name`, `description`, `price`, and `tax`. `Message` simply contains a `message` field to convey error information.

class Item(BaseModel):
    name: str
    description: Union[str, None] = None
    price: float
    tax: Union[float, None] = None

class Message(BaseModel):
    message: str

Define a POST endpoint with custom status code and response model

This is the core of the example. We define a POST endpoint `/items/`. The `status_code=status.HTTP_201_CREATED` argument to `@app.post()` sets the default HTTP status code for a successful response to 201 (Created). The `responses` parameter allows us to specify the response models for different HTTP status codes. In this case, we define a response model for status code 400 (Bad Request), indicating that if the request is invalid, the response will be a `Message` object. Inside the function, we simulate a validation error (if the price is less than or equal to 0). In a real application, this would involve more sophisticated validation logic. If there's a validation error, we return the `status.HTTP_400_BAD_REQUEST` status code along with our custom error message. Otherwise, we return the created item.

@app.post("/items/", status_code=status.HTTP_201_CREATED, responses={400: {"model": Message}})
async def create_item(item: Item):
    # Simulate a validation error for demonstration
    if item.price <= 0:
        return status.HTTP_400_BAD_REQUEST, {"message": "Price must be greater than 0"}
    return item

Running the Application and testing the endpoint

This section contains the instruction on how to run the application and a test case. If the price is less or equal than 0, the request will return the indicated code. FastAPI is handling the code validation

# Run with: uvicorn main:app --reload
# Try sending a POST request with a price <= 0, you will get:
# {"detail":[{"loc":["body","price"],"msg":"ensure this value is greater than 0","type":"value_error.number.not_gt","ctx":{"limit_value":0}}]}}

Concepts behind the snippet

  • HTTP Status Codes: Standardized codes that indicate the outcome of an HTTP request.
  • Response Models: Pydantic models used to define the structure of the response data.
  • Custom Responses: FastAPI allows you to customize the HTTP status code and response body based on the application logic.

Real-Life Use Case Section

Imagine an API for processing payments. A successful payment might return a 200 OK status code with details about the transaction. A failed payment due to insufficient funds might return a 402 Payment Required status code with a message explaining the issue. A 400 Bad Request might indicate invalid input data.

Best Practices

  • Use meaningful HTTP status codes.
  • Define clear response models for different scenarios.
  • Provide informative error messages.

Interview Tip

Be prepared to explain how to use FastAPI's features to control the HTTP status code and structure of API responses. Understand the importance of using appropriate status codes and informative error messages for providing a good developer experience.

When to use them

Use custom status codes and response models when you need to provide more detailed feedback to the client about the outcome of a request. This is especially important for APIs that handle complex operations or require specific error handling.

Memory footprint

Defining explicit status codes and response models doesn't significantly affect the memory footprint of a FastAPI application. The memory usage is primarily determined by the size of the data being processed and the efficiency of the Pydantic models used.

Alternatives

Alternatives to using predefined status code constants include directly specifying the integer value of the status code. However, using the constants from `fastapi.status` makes the code more readable and maintainable. For response models, you could return simple dictionaries or strings, but using Pydantic models provides data validation and automatic API documentation.

Pros

  • Improved clarity: Using meaningful status codes and response models makes the API easier to understand.
  • Better error handling: Providing specific error messages helps clients diagnose and resolve issues.
  • Automatic API documentation: FastAPI automatically documents the different response models.

Cons

  • Slightly more code: Defining response models requires writing additional code compared to returning simple dictionaries.

FAQ

  • What is the purpose of the `status_code` parameter in the route decorator?

    The `status_code` parameter in the route decorator allows you to set the default HTTP status code for a successful response from that endpoint. This helps to explicitly communicate the outcome of the request to the client.
  • How can I return different status codes and response models based on the outcome of a request?

    You can use conditional logic within your route function to return different HTTP status codes and response models. The example above demonstrates returning a 400 Bad Request status code with a custom error message when the price is invalid.
  • Does FastAPI automatically generate documentation for custom status codes and response models?

    Yes, FastAPI automatically generates OpenAPI documentation for the different HTTP status codes and response models that you define using the `responses` parameter in the route decorator.