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
6.4 KiB
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
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)
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
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:
curl -s http://localhost:8000/health
# {"status":"ok","version":"0.1.0"}
Version:
curl -s http://localhost:8000/api/v1/version
# {"app":"newzy","version":"0.1.0"}
Error format
All non-2xx responses use a standardized envelope:
{
"detail": "Not Found",
"code": "not_found"
}
Validation failures (HTTP 422) additionally include per-field errors:
{
"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(defaultfalse) - 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.
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.