When building APIs with FastAPI, it's crucial to provide clear and consistent responses to your clients. This is where response models and status codes come into play. They help you structure your API responses and communicate the outcome of requests effectively.
Response models in FastAPI allow you to define the structure of your API responses. They offer several benefits:
Let's look at how to use response models in FastAPI:
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class UserResponse(BaseModel): id: int name: str email: str @app.get("/users/{user_id}", response_model=UserResponse) async def get_user(user_id: int): # Fetch user from database user = { "id": user_id, "name": "John Doe", "email": "john@example.com", "password": "secret" } return user
In this example, we define a UserResponse
model and use it as the response_model
for our endpoint. FastAPI will:
password
in this case)HTTP status codes are standardized codes used to indicate the outcome of an HTTP request. Using the correct status codes helps clients understand the result of their requests. FastAPI makes it easy to set status codes for your responses.
Here are some common status codes and when to use them:
Let's see how to use status codes in FastAPI:
from fastapi import FastAPI, HTTPException, status app = FastAPI() @app.post("/users/", status_code=status.HTTP_201_CREATED) async def create_user(name: str, email: str): # Create user in database return {"id": 1, "name": name, "email": email} @app.get("/users/{user_id}") async def get_user(user_id: int): if user_id not in user_database: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found") return user_database[user_id]
In this example, we:
HTTPException
to raise a 404 error when a user is not foundYou can use response models and status codes together to create more informative and consistent API responses:
from fastapi import FastAPI, HTTPException, status from pydantic import BaseModel app = FastAPI() class UserResponse(BaseModel): id: int name: str email: str class UserCreate(BaseModel): name: str email: str @app.post("/users/", response_model=UserResponse, status_code=status.HTTP_201_CREATED) async def create_user(user: UserCreate): # Create user in database new_user = {"id": 1, **user.dict()} return new_user @app.get("/users/{user_id}", response_model=UserResponse) async def get_user(user_id: int): if user_id not in user_database: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found") return user_database[user_id]
This approach provides several advantages:
HTTPException
to handle expected errors and provide meaningful responses.By following these practices and effectively using response models and status codes, you'll create more robust, informative, and user-friendly APIs with FastAPI.
15/11/2024 | Python
08/11/2024 | Python
06/10/2024 | Python
22/11/2024 | Python
08/12/2024 | Python
14/11/2024 | Python
15/11/2024 | Python
05/10/2024 | Python
26/10/2024 | Python
06/10/2024 | Python
05/11/2024 | Python
15/10/2024 | Python