📝 Fastapi

HTTPException in FastAPI

P
Author
Pyland
📅
Published
30.06.2026
⏱️
Reading time
1 min
👁️
Views
86
🌿
Level
Medium

Охватываемые темы: Basic Usage, Status Codes, Error Details, Custom Headers.

Basic Usage

from fastapi import FastAPI, HTTPException

app = FastAPI()

@app.get("/tasks/{task_id}")
def get_task(task_id: int):
    task = db.get(task_id)
    if not task:
        raise HTTPException(status_code=404, detail="Task not found")
    return task

Status Codes

from fastapi import HTTPException
from starlette import status

raise HTTPException(status_code=400, detail="Bad request")
raise HTTPException(status_code=401, detail="Not authenticated")
raise HTTPException(status_code=403, detail="Access forbidden")
raise HTTPException(status_code=404, detail="Not found")
raise HTTPException(status_code=422, detail="Validation error")

# Or using constants
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Not found")

Error Details

raise HTTPException(
    status_code=400,
    detail={
        "error": "validation_error",
        "field": "title",
        "message": "Title cannot be empty",
    }
)

Custom Headers

raise HTTPException(
    status_code=401,
    detail="Not authenticated",
    headers={"WWW-Authenticate": "Bearer"},
)

Custom Exception Handler

from fastapi import Request
from fastapi.responses import JSONResponse

class AppException(Exception):
    def __init__(self, message: str, code: str):
        self.message = message
        self.code = code

@app.exception_handler(AppException)
async def app_exception_handler(request: Request, exc: AppException):
    return JSONResponse(
        status_code=400,
        content={"error": exc.code, "message": exc.message},
    )

# Usage
raise AppException(message="Task not found", code="task_not_found")

Global 404 Handler

from fastapi.responses import JSONResponse

@app.exception_handler(404)
async def not_found_handler(request: Request, exc):
    return JSONResponse(
        status_code=404,
        content={"message": "Resource not found"},
    )

Your reaction to the article

💬 Comments (0)

🔐 Sign in to leave a comment
🚪 Login
💭

No comments yet

Be the first to share your opinion about this article!

🔗 Similar

Similar articles

Continue learning with these materials

📝

Middleware and CORS in FastAPI

Allows browser clients to make requests to an API from a different domain.

📅 30.06.2026 👁️ 84
📝

Dependency Injection in FastAPI

Depends — FastAPI's dependency injection system for reusing code across endpoints.

📅 30.06.2026 👁️ 79
📝

Testing FastAPI with pytest

Охватываемые темы: Installation, TestClient (synchronous), Test database, Tests with fixtures.

📅 30.06.2026 👁️ 90

Did you like the article?

Subscribe to our updates and receive new articles first. Grow with PyLand!