Report missing resources
A requested resource does not exist.
FastAPI · Class
FastAPI's HTTPException is raised to send a deliberate client-facing HTTP error. It accepts a status code plus optional JSON-compatible detail data and response headers.
HTTPException is a FastAPI exception for terminating a request with an HTTP error response. Construct it with a status code and optionally include JSON-compatible detail data and response headers, then raise it rather than returning it.
HTTPException(status_code, detail=None, headers=None)| Name | Type | Description |
|---|---|---|
status_code | int | HTTP status code to send to the client. |
detail | Any | Data sent in the JSON response's detail key; defaults to None. |
headers | Mapping[str, str] | None | Headers sent in the response; defaults to None. |
An exception instance to raise; raising it produces the client-facing HTTP error response.
from fastapi import FastAPI, HTTPException
app = FastAPI()
items = {"foo": "The Foo Wrestlers"}
@app.get("/items/{item_id}")
async def read_item(item_id: str):
if item_id not in items:
raise HTTPException(status_code=404, detail="Item not found")
return {"item": items[item_id]}Raises a client-facing 404 response when the requested item is absent.
A requested resource does not exist.
A request contains invalid data or credentials.
The client must receive an authentication challenge header.
HTTPException represents an API error that FastAPI converts into an HTTP response. Its constructor accepts a status code, optional detail payload, and optional headers.
Follow-up: Can detail be structured data? Yes. FastAPI accepts values that can be converted to JSON, including dictionaries and lists.
Raise it with the desired HTTP status code and a message or other JSON-compatible value in detail. FastAPI then sends that information in the response's detail field.
Follow-up: What happens after it is raised? Execution of the current request is aborted, so later code in that path operation does not run.
FastAPI's class inherits from Starlette's HTTPException but permits any JSON-compatible detail value, whereas Starlette's version only accepts strings for detail.
Follow-up: What can headers provide? They can add response headers such as WWW-Authenticate for authentication-related errors.
WebSocketExceptionfastapi.exceptions.HTTPException