import uvicorn
from fastapi import FastAPI, Query, Body, Request, HTTPException, status, Path
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field
from typing import Annotated
class MyCustomException(Exception):
def __init__(self, message="Default custom exception handler message"):
self.message = message
super().__init__(self.message)
def __str__(self):
return self.message
app = FastAPI(description="Checking my fastapi middleware")
@app.exception_handler(MyCustomException)
async def custom_exception_handler(request: Request, exc: MyCustomException):
return JSONResponse(status_code=status.HTTP_401_UNAUTHORIZED, content={"message": str(exc)})
@app.middleware("http")
async def header_check(request: Request, call_next):
auth_header = request.headers.get("x-Auth")
if auth_header != "anilpatro":
raise MyCustomException(message="Authentication failure")
response = await call_next(request)
response.headers["x-auth"] = "validated"
return response
class UserBase(BaseModel):
name: str = Field(description="User name", max_length=10)
sur_name: str | None = Field(description="Optional surname field")
salary: int = Field(default=100, lt=10000)
class User(UserBase):
password: str = Field(description="User password field", max_length=10)
@app.post("/usr/{user_id}")
async def get_user(user: Annotated[User, Body()],
user_id: Annotated[int, Path(description="user id field", gt=0)],
q: Annotated[int, Query(default=1)]):
response = {"user": user.dict(), "user_id": user_id}
if q:
response.update({"q": q})
return response
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)
In the above code the proper curl – curl -X POST “http://0.0.0.0:8000/usr/1?q=5” -H “x-Auth: anilpatro” -H “Content-Type: application/json” -d ‘{“name”: “John”, “sur_name”: “Doe”, “salary”: 900, “password”: “secret”}’
is working fine, how ever for testing purpose – curl -X POST “http://0.0.0.0:8000/usr/1?q=5” -H “x-Auth: wrongheader” -H “Content-Type: application/json” -d ‘{“name”: “John”, “sur_name”: “Doe”, “salary”: 900, “password”: “secret”}’
I am expecting an unauthorised exception. Am I making any mistake while calling exception handler in middleware or fastapi does not support that ?
Appreciate the support 🙂
In the above code the proper curl – curl -X POST “http://0.0.0.0:8000/usr/1?q=5” -H “x-Auth: anilpatro” -H “Content-Type: application/json” -d ‘{“name”: “John”, “sur_name”: “Doe”, “salary”: 900, “password”: “secret”}’
is working fine, how ever for testing purpose – curl -X POST “http://0.0.0.0:8000/usr/1?q=5” -H “x-Auth: wrongheader” -H “Content-Type: application/json” -d ‘{“name”: “John”, “sur_name”: “Doe”, “salary”: 900, “password”: “secret”}’
I am expecting an unauthorised exception. Am I ma`