Files
newz-qwen-27b/backend/core/app.py
Daniel Samson 9a6f75ebd8 feat: add FastAPI backend with SQLite models and Docker setup
Implement milestone M2 (backend setup):

- FastAPI app factory (core/app.py) with CORS, lifespan table
  creation, and global error handlers using a standardized
  {detail, code, errors?} envelope
- Endpoints: GET /health, GET /api/v1/health, GET /api/v1/version
- SQLAlchemy 2.0 ORM: Article, Author, Category models with
  relationships, unique constraints, and FK pragma for SQLite
- Pydantic v2 schemas (create/update/read) for all models
- Env-driven config (DATABASE_URL, CORS_ORIGINS) + .env.example
- pytest suite (19 tests, ~95% coverage) with per-test SQLite
  databases via fixtures
- Dockerfile (python:3.11-slim) and docker-compose.yml with a
  persistent ./data/db volume and healthcheck
2026-10-30 12:44:54 +00:00

112 lines
3.9 KiB
Python

"""Application factory, CORS setup and global error handling.
Every non-2xx response uses the standardized envelope
(``schemas.common.ErrorDetail``)::
{"detail": "<human readable message>", "code": "<machine readable code>"}
with an additional ``errors`` array for validation failures (HTTP 422).
"""
import logging
from contextlib import asynccontextmanager
from collections.abc import AsyncIterator
from fastapi import FastAPI, Request, status
from fastapi.encoders import jsonable_encoder
from fastapi.exceptions import RequestValidationError
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from starlette.exceptions import HTTPException as StarletteHTTPException
from api.v1 import router as api_v1_router
from config import API_V1_PREFIX, APP_NAME, APP_VERSION, get_settings
from db.session import engine
from models import Base
logger = logging.getLogger("newzy")
# Machine-readable codes for the most common HTTP errors.
_HTTP_ERROR_CODES: dict[int, str] = {
400: "bad_request",
401: "unauthorized",
403: "forbidden",
404: "not_found",
405: "method_not_allowed",
409: "conflict",
422: "validation_error",
429: "too_many_requests",
}
def _error_response(status_code: int, detail: str, code: str, errors=None) -> JSONResponse:
"""Build the standardized error envelope as a JSON response."""
payload: dict = {"detail": detail, "code": code}
if errors is not None:
payload["errors"] = jsonable_encoder(errors)
return JSONResponse(status_code=status_code, content=payload)
@asynccontextmanager
async def lifespan(_app: FastAPI) -> AsyncIterator[None]:
"""Create database tables on startup (idempotent for SQLite volumes)."""
Base.metadata.create_all(bind=engine)
logger.info("Database tables ensured (engine: %s)", engine.url)
yield
def create_app() -> FastAPI:
"""Build and configure the FastAPI application."""
settings = get_settings()
app = FastAPI(
title=APP_NAME,
version=APP_VERSION,
description="Backend API for the newzy news web application.",
openapi_url=f"{API_V1_PREFIX}/openapi.json",
lifespan=lifespan,
)
# --- CORS (frontend development) ------------------------------------
app.add_middleware(
CORSMiddleware,
allow_origins=settings.cors_origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# --- Global error handlers -------------------------------------------
@app.exception_handler(StarletteHTTPException)
async def http_exception_handler(request: Request, exc: StarletteHTTPException) -> JSONResponse:
code = _HTTP_ERROR_CODES.get(exc.status_code, "http_error")
return _error_response(exc.status_code, str(exc.detail), code)
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError) -> JSONResponse:
return _error_response(
422,
"Request validation failed.",
"validation_error",
errors=exc.errors(),
)
@app.exception_handler(Exception)
async def unhandled_exception_handler(request: Request, exc: Exception) -> JSONResponse:
logger.exception("Unhandled error processing %s %s", request.method, request.url.path)
return _error_response(
status.HTTP_500_INTERNAL_SERVER_ERROR,
"An unexpected error occurred.",
"internal_error",
)
# --- Routes -----------------------------------------------------------
app.include_router(api_v1_router, prefix=API_V1_PREFIX, tags=["v1"])
@app.get("/health", tags=["health"], summary="Root health check")
async def health() -> dict:
"""Liveness probe (mirrors ``GET /api/v1/health``)."""
return {"status": "ok", "version": APP_VERSION}
return app