## 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.
π Categories
- β‘ JavaScript (1589)
- π PHP (872)
- π Python3 (810)
- π HTML (691)
- βοΈ C# (650)
- π Python (594)
- β Java (552)
- βοΈ PyTorch (534)
- π§ Linux (472)
- βοΈ C (432)
- π¦ jQuery (406)
- π¨ CSS (377)
- π XML (259)
- π¦ jQuery UI (231)
- π― Bootstrap (220)
- βοΈ C++ (215)
- π °οΈ Angular (205)
- π HTML DOM (201)
- π΄ Redis (188)
- π Web Building (142)
- π Vue.js (141)
- π R (131)
- πΌ Pandas (124)
- ποΈ SQL (105)
- βοΈ Docker (86)
- βοΈ TypeScript (73)
- βοΈ Highcharts (70)
- π AI Agent (70)
- βοΈ React (68)
- π Node.js (65)
- βοΈ Machine Learning (60)
- π Git (59)
- π΅ Go (58)
- π Markdown (58)
- π’ NumPy (55)
- π§ͺ Flask (54)
- βοΈ Scala (53)
- ποΈ SQLite (52)
- π JSTL (52)
- βοΈ VS Code (51)
- π MongoDB (49)
- π Perl (48)
- π Ruby (47)
- π Matplotlib (47)
- βοΈ Uncategorized (46)
- π Swift (46)
- ποΈ PostgreSQL (46)
- βοΈ Data Structures (46)
- π Playwright (46)
- π iOS (45)
- ποΈ MySQL (44)
- βοΈ LangChain (43)
- π FastAPI (40)
- βοΈ Ionic (38)
- π Design Patterns (37)
- βοΈ Eclipse (37)
- π¨ CSS3 (34)
- π Lua (34)
- βοΈ Codex (34)
- πΈ Django (32)
- βοΈ OpenCV (32)
- π Rust (31)
- π JSP (31)
- βοΈ Claude Code (31)
- π Pillow (30)
- βοΈ OpenCode (28)
- π AI Skills (27)
- π Flutter (26)
- π Maven (26)
- π¨ Tailwind CSS (25)
- π§ TensorFlow (25)
- π Servlet (24)
- π Dart (23)
- π Assembly (23)
- βοΈ Memcached (22)
- βοΈ SVG (22)
- βοΈ Electron (22)
- π NLP (22)
- π Regex (21)
- π Android (20)
- π£ Kotlin (19)
- π Julia (19)
- π SOAP (17)
- π Selenium (17)
- π PowerShell (17)
- π Sass (16)
- π HTTP (16)
- π Zig (15)
- π AI (15)
- π AJAX (14)
- π Swagger (14)
- βοΈ Scikit-learn (13)
- βοΈ ECharts (13)
- βοΈ Chart.js (13)
- βοΈ Cursor (13)
- βοΈ SciPy (12)
- π RDF (12)
- π Ollama (12)
- π Next.js (12)
- π Plotly Dash (12)
- π JSON (11)
- π RESTful API (11)
- π WSDL (9)
- βοΈ CMake (8)
- π Firebug (7)
- π Nginx (6)
- βΈοΈ Kubernetes (6)
- π Jupyter (6)
- π LaTeX (4)
- π UniApp (4)
- ποΈ SQL Server (1)
YouTip