0
0
FastAPIframework~30 mins

HTTPException usage in FastAPI - Mini Project: Build & Apply

Choose your learning style9 modes available
Using HTTPException in FastAPI
📖 Scenario: You are building a simple FastAPI web service that returns user information. You want to handle cases where the requested user does not exist by sending a proper HTTP error response.
🎯 Goal: Create a FastAPI app with a route /users/{user_id} that returns user data if found. If the user ID is not in the data, raise an HTTPException with status code 404 and a clear error message.
📋 What You'll Learn
Create a dictionary called users with these exact entries: 1: {'name': 'Alice'}, 2: {'name': 'Bob'}, 3: {'name': 'Charlie'}
Create a FastAPI app instance called app
Create a GET route /users/{user_id} that accepts an integer user_id
Inside the route, check if user_id is in users
If user_id is not found, raise HTTPException(status_code=404, detail='User not found')
If found, return the user data dictionary for that user_id
💡 Why This Matters
🌍 Real World
Web APIs often need to handle missing data gracefully by sending proper HTTP error codes and messages.
💼 Career
Knowing how to use HTTPException in FastAPI is essential for backend developers building robust APIs.
Progress0 / 4 steps
1
Create the user data dictionary
Create a dictionary called users with these exact entries: 1: {'name': 'Alice'}, 2: {'name': 'Bob'}, 3: {'name': 'Charlie'}
FastAPI
Need a hint?

Use curly braces to create a dictionary. Keys are numbers 1, 2, 3. Values are dictionaries with key 'name' and the exact names.

2
Create the FastAPI app instance
Import FastAPI from fastapi and create an app instance called app by calling FastAPI()
FastAPI
Need a hint?

Use from fastapi import FastAPI and then app = FastAPI() to create the app.

3
Create the GET route with user_id parameter
Import HTTPException from fastapi. Create a GET route /users/{user_id} using @app.get. Define a function get_user that takes an integer parameter user_id. Inside the function, check if user_id is in users. If not, raise HTTPException(status_code=404, detail='User not found'). If found, return users[user_id].
FastAPI
Need a hint?

Use @app.get('/users/{user_id}') to create the route. Use if user_id not in users: to check. Raise HTTPException with status 404 and detail message if missing.

4
Complete the FastAPI app with proper imports and route
Ensure the code imports FastAPI and HTTPException from fastapi. The app instance is called app. The GET route /users/{user_id} is defined with function get_user(user_id: int). The function raises HTTPException(status_code=404, detail='User not found') if the user is missing, else returns the user data from users dictionary.
FastAPI
Need a hint?

Review your code to confirm all parts are present and correct.