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
This commit is contained in:
1 parent
357a72114b
commit
9a6f75ebd8
32 files changed
+1465
-1
No files matched your search
@@ -0,0 +1,22 @@
|
||||
# Keep the image small: exclude dev-only files from the build context
|
||||
.venv/
|
||||
venv/
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*.egg-info/
|
||||
.pytest_cache/
|
||||
htmlcov/
|
||||
.coverage
|
||||
tests/
|
||||
data/
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
.git/
|
||||
.gitignore
|
||||
Dockerfile
|
||||
.dockerignore
|
||||
README.md
|
||||
pytest.ini
|
||||
*.db
|
||||
*.sqlite
|
||||
@@ -0,0 +1,7 @@
|
||||
# Database connection string (SQLAlchemy URL).
|
||||
# Default points at the data directory mounted as a Docker volume;
|
||||
# for local runs outside Docker any writable path works.
|
||||
DATABASE_URL=sqlite:///./data/db/newzy.db
|
||||
|
||||
# Comma-separated list of origins allowed by CORS (frontend dev server etc.)
|
||||
CORS_ORIGINS=http://localhost:3000,http://127.0.0.1:3000
|
||||
@@ -0,0 +1,30 @@
|
||||
# Python artifacts
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*.egg-info/
|
||||
|
||||
# Environment files
|
||||
.env
|
||||
.venv/
|
||||
venv/
|
||||
|
||||
# Local databases
|
||||
*.db
|
||||
*.sqlite
|
||||
data/
|
||||
|
||||
# Docker
|
||||
.docker/
|
||||
|
||||
# OS files
|
||||
.DS_Store
|
||||
|
||||
# Editor / IDE
|
||||
.idea/
|
||||
.vscode/
|
||||
*~
|
||||
|
||||
# Testing / coverage
|
||||
.coverage
|
||||
htmlcov/
|
||||
.pytest_cache/
|
||||
@@ -0,0 +1,19 @@
|
||||
FROM python:3.11-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Install dependencies first to leverage Docker layer caching
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
# Copy application code
|
||||
COPY . .
|
||||
|
||||
# SQLite database lives on a mounted volume (see docker-compose.yml)
|
||||
VOLUME /app/data/db
|
||||
|
||||
# Expose port
|
||||
EXPOSE 8000
|
||||
|
||||
# Run application
|
||||
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
|
||||
@@ -0,0 +1,199 @@
|
||||
# newzy — Backend
|
||||
|
||||
FastAPI backend for the **newzy** news web application. This milestone (M2)
|
||||
provides the API backbone: application factory, SQLite persistence via
|
||||
SQLAlchemy, core ORM models (`Article`, `Author`, `Category`), Pydantic
|
||||
schemas, standardized error handling, and a unit-tested, containerized
|
||||
deployment path.
|
||||
|
||||
## Project structure
|
||||
|
||||
```
|
||||
backend/
|
||||
├── api/
|
||||
│ └── v1/
|
||||
│ └── __init__.py # /api/v1 routes (health, version)
|
||||
├── core/
|
||||
│ ├── __init__.py # re-exports create_app
|
||||
│ └── app.py # app factory, CORS, global error handlers
|
||||
├── db/
|
||||
│ ├── __init__.py
|
||||
│ └── session.py # engine, session factory, get_db dependency
|
||||
├── models/
|
||||
│ ├── __init__.py
|
||||
│ ├── base.py # declarative Base
|
||||
│ ├── article.py # Article model
|
||||
│ ├── author.py # Author model
|
||||
│ └── category.py # Category model + slugify()
|
||||
├── schemas/
|
||||
│ ├── __init__.py
|
||||
│ ├── article.py # Article request/response schemas
|
||||
│ ├── author.py # Author request/response schemas
|
||||
│ ├── category.py # Category request/response schemas
|
||||
│ └── common.py # Health/Version payloads, ErrorDetail envelope
|
||||
├── tests/
|
||||
│ ├── conftest.py # fixtures: per-test SQLite DB + TestClient
|
||||
│ ├── test_health.py
|
||||
│ ├── test_version.py
|
||||
│ └── test_models.py
|
||||
├── main.py # application entry point (uvicorn target)
|
||||
├── config.py # env-driven settings (DATABASE_URL, CORS_ORIGINS)
|
||||
├── requirements.txt
|
||||
├── Dockerfile
|
||||
├── .dockerignore
|
||||
├── .env.example
|
||||
├── .gitignore
|
||||
└── pytest.ini
|
||||
```
|
||||
|
||||
## Getting started
|
||||
|
||||
### 1. Local development
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
python3 -m venv .venv
|
||||
source .venv/bin/activate
|
||||
pip install -r requirements.txt
|
||||
|
||||
uvicorn main:app --reload
|
||||
```
|
||||
|
||||
The server starts on <http://localhost:8000>. Interactive API docs are
|
||||
served at <http://localhost:8000/docs>.
|
||||
|
||||
The SQLite database file is created automatically at
|
||||
`./data/db/newzy.db` (directory included) on first start.
|
||||
|
||||
### 2. With Docker Compose (from the repository root)
|
||||
|
||||
```bash
|
||||
docker compose up --build
|
||||
```
|
||||
|
||||
This builds the image, maps port `8000`, and persists the SQLite database in
|
||||
`./data/db` on the host.
|
||||
|
||||
### 3. Run the tests
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
pytest
|
||||
```
|
||||
|
||||
Coverage is reported per module (see `pytest.ini`). Tests run against a
|
||||
throwaway SQLite file per test — the real database is never touched.
|
||||
|
||||
## Configuration
|
||||
|
||||
All settings come from environment variables (see `.env.example`):
|
||||
|
||||
| Variable | Default | Description |
|
||||
| --------------- | -------------------------------------- | ------------------------------------ |
|
||||
| `DATABASE_URL` | `sqlite:///./data/db/newzy.db` | SQLAlchemy database URL |
|
||||
| `CORS_ORIGINS` | `http://localhost:3000,http://127.0.0.1:3000` | Comma-separated allowed origins |
|
||||
|
||||
Inside the container the database lives at `/app/data/db/newzy.db` on the
|
||||
mounted volume (see `docker-compose.yml` at the repository root).
|
||||
|
||||
## API endpoints
|
||||
|
||||
| Method | Path | Description |
|
||||
| ------ | --------------- | -------------------------------------------- |
|
||||
| GET | `/health` | Root health check |
|
||||
| GET | `/api/v1/health`| Health check (versioned alternative path) |
|
||||
| GET | `/api/v1/version` | Application name and version |
|
||||
| GET | `/docs` | Interactive OpenAPI documentation (Swagger) |
|
||||
| GET | `/api/v1/openapi.json` | OpenAPI schema |
|
||||
|
||||
### Examples
|
||||
|
||||
Health check:
|
||||
|
||||
```bash
|
||||
curl -s http://localhost:8000/health
|
||||
# {"status":"ok","version":"0.1.0"}
|
||||
```
|
||||
|
||||
Version:
|
||||
|
||||
```bash
|
||||
curl -s http://localhost:8000/api/v1/version
|
||||
# {"app":"newzy","version":"0.1.0"}
|
||||
```
|
||||
|
||||
### Error format
|
||||
|
||||
All non-2xx responses use a standardized envelope:
|
||||
|
||||
```json
|
||||
{
|
||||
"detail": "Not Found",
|
||||
"code": "not_found"
|
||||
}
|
||||
```
|
||||
|
||||
Validation failures (HTTP 422) additionally include per-field errors:
|
||||
|
||||
```json
|
||||
{
|
||||
"detail": "Request validation failed.",
|
||||
"code": "validation_error",
|
||||
"errors": [
|
||||
{
|
||||
"loc": ["body", "title"],
|
||||
"msg": "String should have at least 1 character",
|
||||
"type": "string_too_short"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
| `code` | HTTP | Meaning |
|
||||
| ----------------- | ---- | -------------------------------- |
|
||||
| `bad_request` | 400 | Malformed request |
|
||||
| `unauthorized` | 401 | Missing/invalid credentials |
|
||||
| `forbidden` | 403 | Insufficient permissions |
|
||||
| `not_found` | 404 | Resource does not exist |
|
||||
| `method_not_allowed` | 405 | Method not allowed on resource |
|
||||
| `conflict` | 409 | State conflict (e.g. duplicate) |
|
||||
| `validation_error`| 422 | Request failed schema validation |
|
||||
| `too_many_requests`| 429 | Rate limit exceeded |
|
||||
| `internal_error` | 500 | Unhandled server error |
|
||||
|
||||
## Data model
|
||||
|
||||
```
|
||||
Author 1 ──── * Article * ──── 1 Category
|
||||
```
|
||||
|
||||
- **Article**: `id`, `title` (unique, ≤200 chars), `content`, `author_id` (FK),
|
||||
`category_id` (FK), `created_at`, `published` (default `false`)
|
||||
- **Author**: `id`, `name` (unique, ≤100 chars), `email` (unique, ≤255 chars),
|
||||
`bio` (nullable)
|
||||
- **Category**: `id`, `name` (unique, ≤100 chars), `slug` (unique, ≤100 chars)
|
||||
|
||||
ORM relationships are defined on both sides (`author.articles`,
|
||||
`category.articles`, `article.author`, `article.category`), and SQLite foreign
|
||||
key enforcement is enabled via a `PRAGMA foreign_keys=ON` connection listener.
|
||||
|
||||
## Docker
|
||||
|
||||
The `Dockerfile` builds on `python:3.11-slim`, installs `requirements.txt`,
|
||||
copies the application code, exposes port `8000`, and runs
|
||||
`uvicorn main:app --host 0.0.0.0 --port 8000`.
|
||||
|
||||
```bash
|
||||
docker build -t newzy-backend ./backend
|
||||
docker run --rm -p 8000:8000 -v $(pwd)/data/db:/app/data/db \
|
||||
-e DATABASE_URL=sqlite:///./data/db/newzy.db newzy-backend
|
||||
```
|
||||
|
||||
## Notes & limitations
|
||||
|
||||
- SQLite is fine for development and demos; a production database
|
||||
(e.g. Postgres) will be configured in a later milestone.
|
||||
- No authentication, rate limiting, or pagination yet — those arrive with the
|
||||
article CRUD milestones.
|
||||
- CORS origins are configured for frontend development; validate them before
|
||||
production deployment.
|
||||
@@ -0,0 +1 @@
|
||||
"""API package (versioned route groups)."""
|
||||
@@ -0,0 +1,23 @@
|
||||
"""API v1 routes.
|
||||
|
||||
Mounted under ``/api/v1`` (see ``core.app.create_app``).
|
||||
"""
|
||||
|
||||
from fastapi import APIRouter
|
||||
|
||||
from config import APP_NAME, APP_VERSION
|
||||
from schemas import HealthResponse, VersionResponse
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/health", response_model=HealthResponse, summary="Service health check")
|
||||
def get_health() -> HealthResponse:
|
||||
"""Report service health (alternative path to the root ``/health``)."""
|
||||
return HealthResponse(status="ok", version=APP_VERSION)
|
||||
|
||||
|
||||
@router.get("/version", response_model=VersionResponse, summary="Application version")
|
||||
def get_version() -> VersionResponse:
|
||||
"""Return the application name and version."""
|
||||
return VersionResponse(app=APP_NAME, version=APP_VERSION)
|
||||
@@ -0,0 +1,45 @@
|
||||
"""Application configuration.
|
||||
|
||||
Settings are read from environment variables so the same code runs
|
||||
locally, in Docker (see ``docker-compose.yml``) and in CI.
|
||||
See ``.env.example`` for the documented variable set.
|
||||
"""
|
||||
|
||||
import os
|
||||
from functools import lru_cache
|
||||
|
||||
# --- Application metadata -------------------------------------------------
|
||||
APP_NAME = "newzy"
|
||||
APP_VERSION = "0.1.0"
|
||||
API_V1_PREFIX = "/api/v1"
|
||||
|
||||
# Default location of the SQLite database file (relative to the working
|
||||
# directory). In Docker this resolves inside the mounted volume
|
||||
# (``./data/db`` -> ``/app/data/db`` on the host's ``./data/db``).
|
||||
DEFAULT_DATABASE_URL = "sqlite:///./data/db/newzy.db"
|
||||
|
||||
# Default origins allowed by CORS (frontend dev servers).
|
||||
DEFAULT_CORS_ORIGINS = "http://localhost:3000,http://127.0.0.1:3000"
|
||||
|
||||
|
||||
class Settings:
|
||||
"""Runtime settings loaded from the environment."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.database_url: str = os.getenv("DATABASE_URL", DEFAULT_DATABASE_URL)
|
||||
self.cors_origins: list[str] = [
|
||||
origin.strip()
|
||||
for origin in os.getenv("CORS_ORIGINS", DEFAULT_CORS_ORIGINS).split(",")
|
||||
if origin.strip()
|
||||
]
|
||||
|
||||
@property
|
||||
def is_sqlite(self) -> bool:
|
||||
"""True when the configured database is SQLite."""
|
||||
return self.database_url.startswith("sqlite")
|
||||
|
||||
|
||||
@lru_cache
|
||||
def get_settings() -> Settings:
|
||||
"""Return the cached application settings."""
|
||||
return Settings()
|
||||
@@ -0,0 +1,5 @@
|
||||
"""Core package (application factory and global error handling)."""
|
||||
|
||||
from core.app import create_app
|
||||
|
||||
__all__ = ["create_app"]
|
||||
@@ -0,0 +1,111 @@
|
||||
"""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
|
||||
@@ -0,0 +1 @@
|
||||
"""Database package (engine, session management)."""
|
||||
@@ -0,0 +1,64 @@
|
||||
"""SQLAlchemy engine and session management.
|
||||
|
||||
The engine is created once at import time from ``config.get_settings()``.
|
||||
For SQLite, the parent directory of the database file is created when it
|
||||
does not exist yet (the Docker volume mount provides it in containers),
|
||||
and the ``foreign_keys`` pragma is enabled on every connection because
|
||||
SQLite has it disabled by default.
|
||||
"""
|
||||
|
||||
from collections.abc import Generator
|
||||
from pathlib import Path
|
||||
|
||||
from sqlalchemy import create_engine, event
|
||||
from sqlalchemy.engine import Engine
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
|
||||
from config import get_settings
|
||||
|
||||
settings = get_settings()
|
||||
|
||||
|
||||
def _ensure_sqlite_dir(database_url: str) -> None:
|
||||
"""Create the parent directory of a file-based SQLite database."""
|
||||
prefix = "sqlite:///"
|
||||
if not database_url.startswith(prefix):
|
||||
return
|
||||
db_path = Path(database_url.removeprefix(prefix))
|
||||
if not db_path.parts or db_path.name == ":memory:":
|
||||
return
|
||||
db_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
|
||||
if settings.is_sqlite:
|
||||
_ensure_sqlite_dir(settings.database_url)
|
||||
connect_args: dict = {"check_same_thread": False}
|
||||
else:
|
||||
connect_args = {}
|
||||
|
||||
engine: Engine = create_engine(
|
||||
settings.database_url,
|
||||
connect_args=connect_args,
|
||||
echo=False,
|
||||
)
|
||||
|
||||
if settings.is_sqlite:
|
||||
|
||||
@event.listens_for(engine, "connect")
|
||||
def _enable_foreign_keys(dbapi_connection, _connection_record) -> None: # pragma: no cover
|
||||
"""Enforce foreign key constraints (OFF by default in SQLite)."""
|
||||
cursor = dbapi_connection.cursor()
|
||||
cursor.execute("PRAGMA foreign_keys=ON")
|
||||
cursor.close()
|
||||
|
||||
|
||||
SessionLocal = sessionmaker(bind=engine, autoflush=False, autocommit=False)
|
||||
|
||||
|
||||
def get_db() -> Generator[Session, None, None]:
|
||||
"""FastAPI dependency that yields a database session and always closes it."""
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
@@ -0,0 +1,15 @@
|
||||
"""newzy backend entry point.
|
||||
|
||||
Run locally with:
|
||||
|
||||
uvicorn main:app --reload
|
||||
"""
|
||||
|
||||
from core import create_app
|
||||
|
||||
app = create_app()
|
||||
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
|
||||
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)
|
||||
@@ -0,0 +1,8 @@
|
||||
"""SQLAlchemy ORM models for newzy."""
|
||||
|
||||
from models.article import Article
|
||||
from models.author import Author
|
||||
from models.base import Base
|
||||
from models.category import Category, slugify
|
||||
|
||||
__all__ = ["Article", "Author", "Base", "Category", "slugify"]
|
||||
@@ -0,0 +1,40 @@
|
||||
"""Article model."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from sqlalchemy import Boolean, DateTime, ForeignKey, String, Text
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from models.base import Base
|
||||
|
||||
|
||||
def _utcnow() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
class Article(Base):
|
||||
"""A news article written by an author and filed under a category."""
|
||||
|
||||
__tablename__ = "articles"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
title: Mapped[str] = mapped_column(String(200), unique=True, nullable=False, index=True)
|
||||
content: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
author_id: Mapped[int] = mapped_column(
|
||||
ForeignKey("authors.id"), nullable=False, index=True
|
||||
)
|
||||
category_id: Mapped[int] = mapped_column(
|
||||
ForeignKey("categories.id"), nullable=False, index=True
|
||||
)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), default=_utcnow, nullable=False
|
||||
)
|
||||
published: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
|
||||
|
||||
author: Mapped[Author] = relationship(back_populates="articles")
|
||||
category: Mapped[Category] = relationship(back_populates="articles")
|
||||
|
||||
def __repr__(self) -> str: # pragma: no cover
|
||||
return f"<Article id={self.id} title={self.title!r}>"
|
||||
@@ -0,0 +1,24 @@
|
||||
"""Author model."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import String, Text
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from models.base import Base
|
||||
|
||||
|
||||
class Author(Base):
|
||||
"""A person who writes articles."""
|
||||
|
||||
__tablename__ = "authors"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
name: Mapped[str] = mapped_column(String(100), unique=True, nullable=False)
|
||||
email: Mapped[str] = mapped_column(String(255), unique=True, nullable=False)
|
||||
bio: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
|
||||
articles: Mapped[list[Article]] = relationship(back_populates="author")
|
||||
|
||||
def __repr__(self) -> str: # pragma: no cover
|
||||
return f"<Author id={self.id} name={self.name!r}>"
|
||||
@@ -0,0 +1,7 @@
|
||||
"""Declarative base shared by all ORM models."""
|
||||
|
||||
from sqlalchemy.orm import DeclarativeBase
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
"""Base class for all newzy ORM models."""
|
||||
@@ -0,0 +1,41 @@
|
||||
"""Category model."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import unicodedata
|
||||
|
||||
from sqlalchemy import String
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from models.base import Base
|
||||
|
||||
_SLUG_RE = re.compile(r"[^a-z0-9]+")
|
||||
|
||||
|
||||
def slugify(text: str) -> str:
|
||||
"""Convert an arbitrary string into a URL-friendly slug.
|
||||
|
||||
>>> slugify("Technology & Science")
|
||||
'technology-science'
|
||||
>>> slugify(" Sports ")
|
||||
'sports'
|
||||
"""
|
||||
normalized = unicodedata.normalize("NFKD", text)
|
||||
normalized = normalized.encode("ascii", "ignore").decode("ascii")
|
||||
return _SLUG_RE.sub("-", normalized.lower()).strip("-")
|
||||
|
||||
|
||||
class Category(Base):
|
||||
"""A topic used to group articles."""
|
||||
|
||||
__tablename__ = "categories"
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
name: Mapped[str] = mapped_column(String(100), unique=True, nullable=False)
|
||||
slug: Mapped[str] = mapped_column(String(100), unique=True, nullable=False)
|
||||
|
||||
articles: Mapped[list[Article]] = relationship(back_populates="category")
|
||||
|
||||
def __repr__(self) -> str: # pragma: no cover
|
||||
return f"<Category id={self.id} slug={self.slug!r}>"
|
||||
@@ -0,0 +1,9 @@
|
||||
[pytest]
|
||||
testpaths = tests
|
||||
python_files = test_*.py
|
||||
python_classes = Test*
|
||||
python_functions = test_*
|
||||
asyncio_mode = auto
|
||||
addopts = -v --cov=. --cov-report=term-missing
|
||||
pythonpath = .
|
||||
filterwarnings = ignore::DeprecationWarning
|
||||
@@ -0,0 +1,19 @@
|
||||
# --- Web framework --------------------------------------------------------
|
||||
fastapi>=0.116
|
||||
uvicorn>=0.35
|
||||
|
||||
# --- Database -------------------------------------------------------------
|
||||
SQLAlchemy>=2.0.41
|
||||
|
||||
# --- Schemas / validation ---------------------------------------------------
|
||||
pydantic>=2.11
|
||||
|
||||
# --- Misc runtime -----------------------------------------------------------
|
||||
python-multipart>=0.0.20
|
||||
|
||||
# --- Testing ----------------------------------------------------------------
|
||||
pytest>=8.3
|
||||
pytest-asyncio>=0.25
|
||||
pytest-cov>=6.0
|
||||
# httpx is required by fastapi.testclient.TestClient
|
||||
httpx>=0.28
|
||||
@@ -0,0 +1,24 @@
|
||||
"""Pydantic request/response schemas for newzy."""
|
||||
|
||||
from schemas.article import ArticleBase, ArticleCreate, ArticleRead, ArticleUpdate
|
||||
from schemas.author import AuthorBase, AuthorCreate, AuthorRead, AuthorUpdate
|
||||
from schemas.category import CategoryBase, CategoryCreate, CategoryRead, CategoryUpdate
|
||||
from schemas.common import ErrorDetail, HealthResponse, VersionResponse
|
||||
|
||||
__all__ = [
|
||||
"ArticleBase",
|
||||
"ArticleCreate",
|
||||
"ArticleRead",
|
||||
"ArticleUpdate",
|
||||
"AuthorBase",
|
||||
"AuthorCreate",
|
||||
"AuthorRead",
|
||||
"AuthorUpdate",
|
||||
"CategoryBase",
|
||||
"CategoryCreate",
|
||||
"CategoryRead",
|
||||
"CategoryUpdate",
|
||||
"ErrorDetail",
|
||||
"HealthResponse",
|
||||
"VersionResponse",
|
||||
]
|
||||
@@ -0,0 +1,44 @@
|
||||
"""Schemas for the Article model."""
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
|
||||
class ArticleBase(BaseModel):
|
||||
"""Fields shared by create/update/read article schemas."""
|
||||
|
||||
title: str = Field(..., min_length=1, max_length=200)
|
||||
content: str = Field(..., min_length=1)
|
||||
|
||||
|
||||
class ArticleCreate(ArticleBase):
|
||||
"""Payload for creating an article."""
|
||||
|
||||
author_id: int = Field(..., ge=1)
|
||||
category_id: int = Field(..., ge=1)
|
||||
published: bool = False
|
||||
|
||||
|
||||
class ArticleUpdate(BaseModel):
|
||||
"""Payload for updating an article (all fields optional)."""
|
||||
|
||||
title: str | None = Field(default=None, min_length=1, max_length=200)
|
||||
content: str | None = Field(default=None, min_length=1)
|
||||
author_id: int | None = Field(default=None, ge=1)
|
||||
category_id: int | None = Field(default=None, ge=1)
|
||||
published: bool | None = None
|
||||
|
||||
|
||||
class ArticleRead(BaseModel):
|
||||
"""Article as returned by the API."""
|
||||
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: int
|
||||
title: str
|
||||
content: str
|
||||
author_id: int
|
||||
category_id: int
|
||||
created_at: datetime
|
||||
published: bool
|
||||
@@ -0,0 +1,38 @@
|
||||
"""Schemas for the Author model."""
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
||||
|
||||
|
||||
class AuthorBase(BaseModel):
|
||||
"""Fields shared by create/update/read author schemas."""
|
||||
|
||||
name: str = Field(..., min_length=1, max_length=100)
|
||||
email: str = Field(..., min_length=3, max_length=255)
|
||||
bio: str | None = None
|
||||
|
||||
@field_validator("email")
|
||||
@classmethod
|
||||
def _valid_email(cls, value: str) -> str:
|
||||
if "@" not in value or value.startswith("@") or value.endswith("@"):
|
||||
raise ValueError("must be a valid email address")
|
||||
return value
|
||||
|
||||
|
||||
class AuthorCreate(AuthorBase):
|
||||
"""Payload for creating an author."""
|
||||
|
||||
|
||||
class AuthorUpdate(BaseModel):
|
||||
"""Payload for updating an author (all fields optional)."""
|
||||
|
||||
name: str | None = Field(default=None, min_length=1, max_length=100)
|
||||
email: str | None = Field(default=None, min_length=3, max_length=255)
|
||||
bio: str | None = None
|
||||
|
||||
|
||||
class AuthorRead(AuthorBase):
|
||||
"""Author as returned by the API."""
|
||||
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: int
|
||||
@@ -0,0 +1,51 @@
|
||||
"""Schemas for the Category model."""
|
||||
|
||||
import re
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from models.category import slugify
|
||||
|
||||
_SLUG_PATTERN = r"^[a-z0-9]+(?:-[a-z0-9]+)*$"
|
||||
|
||||
|
||||
class CategoryBase(BaseModel):
|
||||
"""Fields shared by category schemas."""
|
||||
|
||||
name: str = Field(..., min_length=1, max_length=100)
|
||||
slug: str | None = Field(
|
||||
default=None,
|
||||
min_length=1,
|
||||
max_length=100,
|
||||
pattern=_SLUG_PATTERN,
|
||||
description="URL-friendly identifier; derived from `name` when omitted.",
|
||||
)
|
||||
|
||||
|
||||
class CategoryCreate(CategoryBase):
|
||||
"""Payload for creating a category.
|
||||
|
||||
When ``slug`` is omitted it is generated from ``name``.
|
||||
"""
|
||||
|
||||
|
||||
class CategoryUpdate(BaseModel):
|
||||
"""Payload for updating a category (all fields optional)."""
|
||||
|
||||
name: str | None = Field(default=None, min_length=1, max_length=100)
|
||||
slug: str | None = Field(default=None, min_length=1, max_length=100, pattern=_SLUG_PATTERN)
|
||||
|
||||
|
||||
class CategoryRead(BaseModel):
|
||||
"""Category as returned by the API."""
|
||||
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: int
|
||||
name: str
|
||||
slug: str
|
||||
|
||||
|
||||
def prepare_slug(create: CategoryCreate) -> str:
|
||||
"""Resolve the slug to store: explicit slug or one derived from the name."""
|
||||
return create.slug if create.slug is not None else slugify(create.name)
|
||||
@@ -0,0 +1,29 @@
|
||||
"""Shared response schemas and the standardized error envelope."""
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class ErrorDetail(BaseModel):
|
||||
"""Standard error payload returned for all non-2xx responses.
|
||||
|
||||
``errors`` is only present for validation failures (HTTP 422) and
|
||||
carries the per-field details.
|
||||
"""
|
||||
|
||||
detail: str
|
||||
code: str
|
||||
errors: list[dict] | None = None
|
||||
|
||||
|
||||
class HealthResponse(BaseModel):
|
||||
"""Payload of the health check endpoints."""
|
||||
|
||||
status: str = "ok"
|
||||
version: str
|
||||
|
||||
|
||||
class VersionResponse(BaseModel):
|
||||
"""Payload of the version endpoint."""
|
||||
|
||||
app: str
|
||||
version: str
|
||||
@@ -0,0 +1,78 @@
|
||||
"""Shared pytest fixtures for the newzy backend test suite.
|
||||
|
||||
The application is pointed at a throwaway SQLite file *before* it is
|
||||
imported, so the module-level engine created in ``db.session`` never
|
||||
touches the real database.
|
||||
"""
|
||||
|
||||
import os
|
||||
import tempfile
|
||||
from collections.abc import Iterator
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
from sqlalchemy import Engine, create_engine, event
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
|
||||
# --- Point the application at a temporary database before import ---------
|
||||
_TMP_DB_FD, _TMP_DB_PATH = tempfile.mkstemp(suffix=".db")
|
||||
os.close(_TMP_DB_FD)
|
||||
os.environ["DATABASE_URL"] = f"sqlite:///{_TMP_DB_PATH}"
|
||||
|
||||
from db.session import get_db # noqa: E402
|
||||
from main import app # noqa: E402
|
||||
from models import Base # noqa: E402
|
||||
|
||||
|
||||
def _enable_foreign_keys(dbapi_connection, _connection_record) -> None:
|
||||
"""Mirror the FK pragma applied to the production engine (see db.session)."""
|
||||
cursor = dbapi_connection.cursor()
|
||||
cursor.execute("PRAGMA foreign_keys=ON")
|
||||
cursor.close()
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def engine() -> Iterator[Engine]:
|
||||
"""A fresh SQLite database per test (created and destroyed around it)."""
|
||||
fd, path = tempfile.mkstemp(suffix=".db")
|
||||
os.close(fd)
|
||||
test_engine = create_engine(
|
||||
f"sqlite:///{path}", connect_args={"check_same_thread": False}
|
||||
)
|
||||
event.listen(test_engine, "connect", _enable_foreign_keys)
|
||||
Base.metadata.create_all(test_engine)
|
||||
try:
|
||||
yield test_engine
|
||||
finally:
|
||||
test_engine.dispose()
|
||||
Path(path).unlink(missing_ok=True)
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def session(engine: Engine) -> Iterator[Session]:
|
||||
"""A SQLAlchemy session bound to the per-test database."""
|
||||
TestingSession = sessionmaker(bind=engine, autoflush=False, autocommit=False)
|
||||
db = TestingSession()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def client(engine: Engine) -> Iterator[TestClient]:
|
||||
"""A FastAPI TestClient whose ``get_db`` dependency is overridden per test."""
|
||||
TestingSession = sessionmaker(bind=engine, autoflush=False, autocommit=False)
|
||||
|
||||
def override_get_db() -> Iterator[Session]:
|
||||
db = TestingSession()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
app.dependency_overrides[get_db] = override_get_db
|
||||
with TestClient(app) as test_client:
|
||||
yield test_client
|
||||
app.dependency_overrides.clear()
|
||||
@@ -0,0 +1,29 @@
|
||||
"""Tests for the health check endpoints."""
|
||||
|
||||
|
||||
def test_health_returns_200_ok(client) -> None:
|
||||
response = client.get("/health")
|
||||
assert response.status_code == 200
|
||||
|
||||
|
||||
def test_health_returns_expected_json_structure(client) -> None:
|
||||
payload = client.get("/health").json()
|
||||
assert payload["status"] == "ok"
|
||||
assert "version" in payload
|
||||
|
||||
|
||||
def test_api_v1_health_returns_200_ok(client) -> None:
|
||||
"""The alternative health path ``/api/v1/health`` must behave the same."""
|
||||
response = client.get("/api/v1/health")
|
||||
assert response.status_code == 200
|
||||
payload = response.json()
|
||||
assert payload["status"] == "ok"
|
||||
assert "version" in payload
|
||||
|
||||
|
||||
def test_unknown_route_returns_standardized_error(client) -> None:
|
||||
response = client.get("/api/v1/does-not-exist")
|
||||
assert response.status_code == 404
|
||||
payload = response.json()
|
||||
assert payload["code"] == "not_found"
|
||||
assert "detail" in payload
|
||||
@@ -0,0 +1,137 @@
|
||||
"""Tests for ORM model instantiation and database operations."""
|
||||
|
||||
import pytest
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from models import Article, Author, Category, slugify
|
||||
|
||||
|
||||
class TestAuthor:
|
||||
def test_create_and_commit(self, session) -> None:
|
||||
author = Author(
|
||||
name="Ada Lovelace", email="ada@example.com", bio="First programmer."
|
||||
)
|
||||
session.add(author)
|
||||
session.commit()
|
||||
session.refresh(author)
|
||||
assert author.id is not None
|
||||
assert session.get(Author, author.id).email == "ada@example.com"
|
||||
|
||||
def test_unique_name_enforced(self, session) -> None:
|
||||
session.add(Author(name="Grace Hopper", email="grace@example.com"))
|
||||
session.commit()
|
||||
session.add(Author(name="Grace Hopper", email="other@example.com"))
|
||||
with pytest.raises(IntegrityError):
|
||||
session.commit()
|
||||
session.rollback()
|
||||
|
||||
def test_unique_email_enforced(self, session) -> None:
|
||||
session.add(Author(name="Grace Hopper", email="grace@example.com"))
|
||||
session.commit()
|
||||
session.add(Author(name="Another Person", email="grace@example.com"))
|
||||
with pytest.raises(IntegrityError):
|
||||
session.commit()
|
||||
session.rollback()
|
||||
|
||||
def test_bio_is_nullable(self, session) -> None:
|
||||
author = Author(name="Alan Turing", email="alan@example.com")
|
||||
session.add(author)
|
||||
session.commit()
|
||||
session.refresh(author)
|
||||
assert author.bio is None
|
||||
|
||||
|
||||
class TestCategory:
|
||||
def test_create_and_commit(self, session) -> None:
|
||||
category = Category(name="Technology", slug="technology")
|
||||
session.add(category)
|
||||
session.commit()
|
||||
session.refresh(category)
|
||||
assert category.id is not None
|
||||
assert session.get(Category, category.id).name == "Technology"
|
||||
|
||||
def test_unique_name_enforced(self, session) -> None:
|
||||
session.add(Category(name="Science", slug="science"))
|
||||
session.commit()
|
||||
session.add(Category(name="Science", slug="science-2"))
|
||||
with pytest.raises(IntegrityError):
|
||||
session.commit()
|
||||
session.rollback()
|
||||
|
||||
def test_unique_slug_enforced(self, session) -> None:
|
||||
session.add(Category(name="Science", slug="science"))
|
||||
session.commit()
|
||||
session.add(Category(name="Science News", slug="science"))
|
||||
with pytest.raises(IntegrityError):
|
||||
session.commit()
|
||||
session.rollback()
|
||||
|
||||
def test_slug_generation(self) -> None:
|
||||
assert slugify("Technology & Science") == "technology-science"
|
||||
assert slugify(" Sports ") == "sports"
|
||||
assert slugify("Already-fine") == "already-fine"
|
||||
assert slugify("Café News") == "cafe-news"
|
||||
|
||||
|
||||
class TestArticle:
|
||||
def _make_author_category(self, session) -> tuple[Author, Category]:
|
||||
author = Author(name="Byline Writer", email="writer@example.com")
|
||||
category = Category(name="World", slug="world")
|
||||
session.add_all([author, category])
|
||||
session.commit()
|
||||
session.refresh(author)
|
||||
session.refresh(category)
|
||||
return author, category
|
||||
|
||||
def test_create_and_commit(self, session) -> None:
|
||||
author, category = self._make_author_category(session)
|
||||
article = Article(
|
||||
title="First post",
|
||||
content="Hello world.",
|
||||
author_id=author.id,
|
||||
category_id=category.id,
|
||||
)
|
||||
session.add(article)
|
||||
session.commit()
|
||||
session.refresh(article)
|
||||
assert article.id is not None
|
||||
assert article.created_at is not None
|
||||
assert article.published is False
|
||||
|
||||
def test_foreign_key_relationships(self, session) -> None:
|
||||
author, category = self._make_author_category(session)
|
||||
article = Article(
|
||||
title="Related",
|
||||
content="Body text.",
|
||||
author_id=author.id,
|
||||
category_id=category.id,
|
||||
)
|
||||
session.add(article)
|
||||
session.commit()
|
||||
assert article.author.name == author.name
|
||||
assert article.category.slug == "world"
|
||||
assert article in author.articles
|
||||
assert article in category.articles
|
||||
|
||||
def test_unique_title_enforced(self, session) -> None:
|
||||
author, category = self._make_author_category(session)
|
||||
session.add(
|
||||
Article(title="Dup", content="one", author_id=author.id, category_id=category.id)
|
||||
)
|
||||
session.commit()
|
||||
session.add(
|
||||
Article(title="Dup", content="two", author_id=author.id, category_id=category.id)
|
||||
)
|
||||
with pytest.raises(IntegrityError):
|
||||
session.commit()
|
||||
session.rollback()
|
||||
|
||||
def test_foreign_key_enforced(self, session) -> None:
|
||||
author, category = self._make_author_category(session)
|
||||
article = Article(
|
||||
title="Orphan", content="No such author.", author_id=9999, category_id=category.id
|
||||
)
|
||||
session.add(article)
|
||||
with pytest.raises(IntegrityError):
|
||||
session.commit()
|
||||
session.rollback()
|
||||
@@ -0,0 +1,23 @@
|
||||
"""Tests for the version endpoint."""
|
||||
|
||||
import re
|
||||
|
||||
_SEMVER = re.compile(r"^\d+\.\d+\.\d+$")
|
||||
|
||||
|
||||
def test_version_returns_200_ok(client) -> None:
|
||||
response = client.get("/api/v1/version")
|
||||
assert response.status_code == 200
|
||||
|
||||
|
||||
def test_version_response_format(client) -> None:
|
||||
payload = client.get("/api/v1/version").json()
|
||||
assert payload["app"] == "newzy"
|
||||
assert _SEMVER.match(payload["version"]), f"unexpected version format: {payload['version']}"
|
||||
|
||||
|
||||
def test_version_matches_configured_app_version(client) -> None:
|
||||
from config import APP_VERSION
|
||||
|
||||
payload = client.get("/api/v1/version").json()
|
||||
assert payload["version"] == APP_VERSION
|
||||
Reference in new issue
Block a user