YouTip LogoYouTip

Fastapi Status Code 2

## Handling HTTP Status Codes in FastAPI In web development, HTTP status codes are a crucial part of the server's response. They inform the client (such as a browser, mobile app, or another API) about the outcome of their request. FastAPI makes it incredibly easy to declare, manage, and customize these status codes. You can define a default status code directly in your path operation decorators, or dynamically alter them within your path functions. --- ## Declaring a Default Status Code To declare the default HTTP status code for a response, use the `status_code` parameter inside your path operation decorator (such as `@app.post()`, `@app.get()`, etc.). ### Example: Creating a Resource (201 Created) ```python from fastapi import FastAPI, status app = FastAPI() # When creating a resource, use the 201 Created status code @app.post("/items/", status_code=status.HTTP_201_CREATED) async def create_item(name: str): return {"name": name} ``` > **Note:** The `status_code` parameter belongs to the decorator method (e.g., `@app.post()`), not to your path operation function. While you can pass a raw integer (like `201`), it is highly recommended to use the constants provided by `fastapi.status` for better code readability and IDE autocompletion. --- ## HTTP Status Code Quick Reference HTTP status codes are grouped into five categories based on their behavior: | Range | Category | Common Status Code | Meaning | | :--- | :--- | :--- | :--- | | **1xx** | Informational | -- | Request received, continuing process (rarely used directly). | | **2xx** | Success | `200 OK`
`201 Created`
`204 No Content` | Request successfully processed (200 is default).
Resource successfully created.
Request succeeded, but there is no content to return. | | **3xx** | Redirection | `304 Not Modified` | Resource has not been modified (cached version can be used). | | **4xx** | Client Error | `400 Bad Request`
`401 Unauthorized`
`403 Forbidden`
`404 Not Found` | Bad request syntax or invalid parameters.
Authentication is required or has failed.
Authenticated, but lacks permission to access the resource.
The requested resource could not be found. | | **5xx** | Server Error | `500 Internal Server Error` | The server encountered an unexpected condition. | --- ## Using `fastapi.status` Constants FastAPI provides a dedicated `status` module containing convenient constants for all standard HTTP status codes. Using these constants prevents typos and enables your editor to provide autocomplete suggestions. ### Comprehensive Example ```python from fastapi import FastAPI, status app = FastAPI() # POST - Create a resource, returns 201 Created @app.post("/items/", status_code=status.HTTP_201_CREATED) async def create_item(name: str): return {"name": name} # DELETE - Remove a resource, returns 204 No Content @app.delete("/items/{item_id}", status_code=status.HTTP_204_NO_CONTENT) async def delete_item(item_id: int): # Delete operations typically do not return any content body pass # GET - Retrieve a resource, returns 200 OK (Default behavior) @app.get("/items/{item_id}") async def read_item(item_id: int): return {"item_id": item_id} ``` > **Important Note on 204 No Content:** The `204 No Content` status code indicates that the request succeeded but the response body must be empty. If you return data in a path operation configured with `204`, FastAPI will strip the response body automatically to comply with the HTTP specification. --- ## Common Status Code Constants Reference Here is a list of the most frequently used status code constants in `fastapi.status` and their typical use cases: | Constant | Value | Typical Use Case | | :--- | :--- | :--- | | `status.HTTP_200_OK` | `200` | Standard successful `GET`, `PUT`, or `PATCH` requests. | | `status.HTTP_201_CREATED` | `201` | Successful `POST` requests that result in resource creation. | | `status.HTTP_204_NO_CONTENT` | `204` | Successful `DELETE` requests where no response body is needed. | | `status.HTTP_400_BAD_REQUEST` | `400` | Invalid client input or malformed request payload. | | `status.HTTP_401_UNAUTHORIZED` | `401` | Missing or invalid authentication credentials (e.g., expired token). | | `status.HTTP_403_FORBIDDEN` | `403` | The client is authenticated but does not have permission to access the resource. | | `status.HTTP_404_NOT_FOUND` | `404` | The requested database record or endpoint does not exist. | | `status.HTTP_409_CONFLICT` | `409` | Resource conflict, such as trying to register an email that already exists. | | `status.HTTP_422_UNPROCESSABLE_ENTITY` | `422` | Request validation failed (FastAPI raises this automatically for invalid schemas). | | `status.HTTP_500_INTERNAL_SERVER_ERROR` | `500` | Unhandled exceptions or server-side crashes. | --- ## Summary - **Declare Default Status Codes:** Use the `status_code` parameter in your path operation decorators (e.g., `@app.post("/path", status_code=201)`). - **Use Constants:** Import and use `from fastapi import status` to leverage IDE autocompletion and write cleaner, self-documenting code. - **Best Practices:** - Use **`201 Created`** for successful resource creation (`POST`). - Use **`204 No Content`** for successful deletions (`DELETE`). - Use **`200 OK`** (default) for standard retrievals (`GET`) and updates (`PUT`/`PATCH`). - **Error Handling:** Use `4xx` status codes to indicate client-side errors and `5xx` status codes for unexpected server-side errors.
← Fastapi Header CookieFastapi Response Model β†’