0
0
FastAPIframework~30 mins

Custom error response models in FastAPI - Mini Project: Build & Apply

Choose your learning style9 modes available
Custom error response models in FastAPI
📖 Scenario: You are building a simple API that returns user information. You want to handle errors clearly by sending custom error messages in a structured way.
🎯 Goal: Create a FastAPI app that returns user data for a given user ID. If the user ID is not found, return a custom error response model with a clear message and error code.
📋 What You'll Learn
Create a dictionary called users with user IDs as keys and names as values.
Create a Pydantic model called ErrorResponse with fields error_code (int) and message (str).
Create a GET endpoint /users/{user_id} that returns the user name if found.
If the user ID is not found, return a JSON response using the ErrorResponse model with error_code 404 and a message User not found.
💡 Why This Matters
🌍 Real World
APIs often need to send clear error messages to clients. Custom error response models help keep error data consistent and easy to understand.
💼 Career
Backend developers use FastAPI and Pydantic to build APIs with clear error handling, improving user experience and debugging.
Progress0 / 4 steps
1
Create the initial user data dictionary
Create a dictionary called users with these exact entries: 1: "Alice", 2: "Bob", 3: "Charlie".
FastAPI
Need a hint?

Use curly braces to create a dictionary with keys 1, 2, 3 and values "Alice", "Bob", "Charlie".

2
Define the custom error response model
Import BaseModel from pydantic and create a class called ErrorResponse that inherits from BaseModel. It should have two fields: error_code of type int and message of type str.
FastAPI
Need a hint?

Use class ErrorResponse(BaseModel): and define the two fields with type annotations.

3
Create the FastAPI app and GET endpoint
Import FastAPI and HTTPException from fastapi. Create a FastAPI app called app. Define a GET endpoint /users/{user_id} that takes user_id as an int path parameter. If user_id is in users, return a dictionary with key name and the user name as value.
FastAPI
Need a hint?

Use @app.get("/users/{user_id}") decorator and an async function with user_id: int parameter.

4
Return custom error response when user not found
In the get_user function, if user_id is not in users, raise HTTPException with status_code=404 and detail set to an instance of ErrorResponse with error_code=404 and message="User not found".
FastAPI
Need a hint?

Use raise HTTPException(status_code=404, detail=ErrorResponse(error_code=404, message="User not found").dict()) to send the custom error response.