๐Ÿ“ Fastapi

HTTPException in FastAPI

P
Author
PyLand Team
๐Ÿ“…
Published
30.06.2026
โฑ๏ธ
Reading time
1 min
๐Ÿ‘๏ธ
Views
298
๐ŸŒฟ
Level
Medium

Covered topics: 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

Middleware processes requests and responses around FastAPI routes, while CORS controls which browser origins may...

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 330
๐Ÿ“

Dependency Injection in FastAPI

Depends โ€” FastAPI's dependency injection system for reusing code across endpoints.

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 304
๐Ÿ“

Testing FastAPI with pytest

Covered topics: Installation, TestClient (synchronous), Test database, Tests with fixtures.

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 341
๐ŸŽ“ Continue learning

Courses that cover this material

Visit the course to apply this material in practice.

FastAPI: From First Route to an AI-Powered Site Open course curriculum