Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion backend/app/api/deps.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
from typing import Annotated

import jwt
from fastapi import Depends, HTTPException, status
from fastapi import Depends, HTTPException, status, Request
from fastapi.responses import JSONResponse
from fastapi.security import OAuth2PasswordBearer
from jwt.exceptions import InvalidTokenError
from pydantic import ValidationError
Expand All @@ -12,6 +13,7 @@
from app.core.config import settings
from app.core.db import engine
from app.models import TokenPayload, User
from app.utils import APIResponse

reusable_oauth2 = OAuth2PasswordBearer(
tokenUrl=f"{settings.API_V1_STR}/login/access-token"
Expand Down Expand Up @@ -55,3 +57,12 @@ def get_current_active_superuser(current_user: CurrentUser) -> User:
status_code=403, detail="The user doesn't have enough privileges"
)
return current_user

async def http_exception_handler(request: Request, exc: HTTPException):
"""
Global handler for HTTPException to return standardized response format.
"""
return JSONResponse(
status_code=exc.status_code,
content=APIResponse.failure_response(exc.detail).model_dump() | {"detail": exc.detail}, # TEMPORARY: Keep "detail" for backward compatibility
)
7 changes: 5 additions & 2 deletions backend/app/main.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import sentry_sdk
from fastapi import FastAPI

from fastapi import FastAPI, HTTPException
from fastapi.routing import APIRoute
from starlette.middleware.cors import CORSMiddleware

from app.api.main import api_router
from app.api.deps import http_exception_handler
from app.core.config import settings


def custom_generate_unique_id(route: APIRoute) -> str:
return f"{route.tags[0]}-{route.name}"

Expand All @@ -31,3 +32,5 @@ def custom_generate_unique_id(route: APIRoute) -> str:
)

app.include_router(api_router, prefix=settings.API_V1_STR)

app.add_exception_handler(HTTPException, http_exception_handler)
20 changes: 19 additions & 1 deletion backend/app/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Any
from typing import Any, Dict, Generic, Optional, TypeVar

import emails # type: ignore
import jwt
Expand All @@ -12,9 +12,27 @@
from app.core import security
from app.core.config import settings

from typing import Generic, Optional, TypeVar
from pydantic import BaseModel

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

T = TypeVar("T")

class APIResponse(BaseModel, Generic[T]):
success: bool
data: Optional[T] = None
error: Optional[str] = None

@classmethod
def success_response(cls, data: T) -> "APIResponse[T]":
return cls(success=True, data=data, error=None)

@classmethod
def failure_response(cls, error: str) -> "APIResponse[None]":
return cls(success=False, data=None, error=error)


@dataclass
class EmailData:
Expand Down