Introduction
HTTPException lets you send error messages with HTTP status codes in FastAPI. It helps tell users what went wrong clearly.
Jump into concepts and practice - no test required
HTTPException lets you send error messages with HTTP status codes in FastAPI. It helps tell users what went wrong clearly.
from fastapi import HTTPException raise HTTPException(status_code=404, detail="Item not found")
status_code to set the HTTP error code like 404 or 400.detail to provide a clear error message for the client.raise HTTPException(status_code=404, detail="User not found")
raise HTTPException(status_code=400, detail="Invalid input data")
raise HTTPException(status_code=403, detail="Access denied")
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.
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]}
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.
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.
HTTPException in FastAPI?raise HTTPException(status_code=404, detail="Item not found").from fastapi import FastAPI, HTTPException
app = FastAPI()
items = {"apple": "A juicy fruit"}
@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": items[item_name]}from fastapi import FastAPI, HTTPException
app = FastAPI()
@app.get("/users/{user_id}")
def get_user(user_id: int):
if user_id < 0:
HTTPException(status_code=400, detail="Invalid user ID")
return {"user_id": user_id}