FastAPI API Key Header Raises Starlette HTTPException Instead of FastAPI.HTTPException
FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints. FastAPI is built on top of Starlette, which provides the ASGI (Asynchronous Server Gateway Interface) application framework.
One key concept in FastAPI is the use of exceptions to handle errors and unexpected conditions. FastAPI defines its own HTTPException exception, which extends the Starlette HTTPException class. However, there is a scenario where using FastAPI.HTTPException will raise a Starlette HTTPException instead.
Key Concepts
- FastAPI is a web framework for building APIs with Python.
- FastAPI is built on top of Starlette, which provides the ASGI application framework.
- FastAPI defines its own HTTPException exception, which extends the Starlette HTTPException class.
Applications
Understanding how FastAPI handles exceptions is crucial when building APIs with this framework. In particular, it is important to know how FastAPI's HTTPException class differs from Starlette's HTTPException class.
Significance
When using FastAPI's HTTPException class, it is possible to raise a Starlette HTTPException instead. This can occur when the status code passed to the HTTPException constructor is not a valid HTTP status code. In this case, FastAPI will raise a Starlette HTTPException with a status code of 400 (Bad Request) and a default message.
Code Example
Here is an example of how to use FastAPI's HTTPException class:
from fastapi import FastAPI, HTTPException
app = FastAPI()
@app.get("/items/{item_id}")
async def read_item(item_id: int, q: str = None):
if item_id < 0:
raise HTTPException(status_code=400, detail="Item ID cannot be negative")
return {"item_id": item_id, "q": q}
In this example, if the item ID is less than 0, the HTTPException class is raised with a status code of 400 and a custom message. However, if an invalid status code is passed to the HTTPException constructor, a Starlette HTTPException will be raised instead:
raise HTTPException(status_code=999, detail="Invalid status code")
In this case, a Starlette HTTPException with a status code of 400 and a default message will be raised.
- FastAPI is a web framework for building APIs with Python.
- FastAPI defines its own HTTPException exception, which extends the Starlette HTTPException class.
- When using FastAPI's HTTPException class, it is possible to raise a Starlette HTTPException instead.
- This can occur when the status code passed to the HTTPException constructor is not a valid HTTP status code.