0
0
FastAPIframework~5 mins

HTTPException usage in FastAPI

Choose your learning style9 modes available
Introduction

HTTPException lets you send error messages with HTTP status codes in FastAPI. It helps tell users what went wrong clearly.

When a requested item is not found in a database.
When a user sends invalid data to your API.
When access is denied due to missing permissions.
When a required parameter is missing in the request.
When the server cannot process the request due to client error.
Syntax
FastAPI
from fastapi import HTTPException

raise HTTPException(status_code=404, detail="Item not found")
Use status_code to set the HTTP error code like 404 or 400.
Use detail to provide a clear error message for the client.
Examples
Raises a 404 error with a message saying the user was not found.
FastAPI
raise HTTPException(status_code=404, detail="User not found")
Raises a 400 error when the client sends bad data.
FastAPI
raise HTTPException(status_code=400, detail="Invalid input data")
Raises a 403 error when the user is not allowed to access a resource.
FastAPI
raise HTTPException(status_code=403, detail="Access denied")
Sample Program

This FastAPI app has a list of items. When you ask for an item by name, it returns the description. If the item is missing, it sends a 404 error with a message.

FastAPI
from fastapi import FastAPI, HTTPException

app = FastAPI()

items = {"apple": "A tasty fruit", "carrot": "A healthy vegetable"}

@app.get("/items/{item_name}")
async def read_item(item_name: str):
    if item_name not in items:
        raise HTTPException(status_code=404, detail="Item not found")
    return {"item": item_name, "description": items[item_name]}
OutputSuccess
Important Notes

Always provide a helpful detail message so users understand the error.

Use standard HTTP status codes to follow web conventions.

HTTPException stops the request and sends the error immediately.

Summary

HTTPException is used to send HTTP errors with messages in FastAPI.

Set status_code and detail to explain the error.

It helps your API communicate problems clearly to users.