Add frontend project structure with React/TypeScript setup

This commit is contained in:
Newzy Developer committed 2026-10-30 10:53:31 +00:00
1 parent c7abb73c66
commit 6914a6855c
58 files changed
+9056 -236

No files matched your search

+29
View File
@@ -0,0 +1,29 @@
# Python artifacts
__pycache__/
*.py[cod]
*.egg-info/
.env
.venv/
venv/
# Database files
*.db
*.sqlite
# Docker files
Dockerfile
.docker/
# OS generated
.DS_Store
# IDE configs
.idea/
.vscode/
*~
# Test coverage
.coverage
htmlcov/
.pytest_cache/
.coverage.*
+200
View File
@@ -0,0 +1,200 @@
# Newzy Backend API
FastAPI backend for the Newzy news web application.
## Overview
This repository contains the backend infrastructure for the Newzy news platform, built using Python FastAPI with SQLAlchemy ORM and SQLite database.
## Features
- RESTful API endpoints
- SQLAlchemy database models
- Pydantic request/response validation
- Docker containerization support
- Unit testing with pytest
- Health and version monitoring endpoints
## Installation
### Local Development
1. Create a virtual environment:
```bash
python -m venv .venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate
```
2. Install dependencies:
```bash
pip install -r requirements.txt
```
3. Set up environment variables (optional):
```bash
export DATABASE_URL="sqlite:///./data/db/newzy.db"
```
4. Run the application:
```bash
uvicorn main:app --reload
```
The API will be available at `http://localhost:8000`
### Using Docker
1. Build and run with Docker Compose:
```bash
docker-compose up -d backend
```
2. Access the API at `http://localhost:8000`
## API Endpoints
### Health Check
#### GET /health
Check if the application is running.
**Response:**
```json
{
"status": "healthy"
}
```
#### GET /api/v1/version
Get application version information.
**Response:**
```json
{
"version": "0.1.0",
"application": "Newzy"
}
```
### Models
The following models are defined in the database:
- **Article**: News articles with title, content, author, and category
- **Author**: Authors who write articles (name, email, bio)
- **Category**: Content categories for organizing articles (name, slug)
## Database Schema
### Articles Table
- `id`: Integer (primary key)
- `title`: String(200), unique
- `content`: Text
- `author_id`: Integer (foreign key to authors.id)
- `category_id`: Integer (foreign key to categories.id)
- `created_at`: DateTime
- `published`: Boolean, default False
### Authors Table
- `id`: Integer (primary key)
- `name`: String(100), unique
- `email`: String(255), unique
- `bio`: Text (nullable)
### Categories Table
- `id`: Integer (primary key)
- `name`: String(100), unique
- `slug`: String(100), unique
## Testing
Run the test suite:
```bash
pytest -v --cov=. --cov-report=html
```
Coverage report will be generated in `htmlcov/` directory.
### Running Specific Tests
```bash
# Run all tests
pytest -v
# Run specific test file
pytest tests/test_models.py -v
# Run with coverage
pytest -v --cov=. --cov-report=term-missing
```
## Configuration
Environment variables available:
| Variable | Description | Default |
|----------|-------------|---------|
| `APP_NAME` | Application name | "Newzy" |
| `APP_VERSION` | Application version | "0.1.0" |
| `DEBUG` | Debug mode | False |
| `DATABASE_URL` | Database connection string | sqlite:///./data/db/newzy.db |
| `CORS_ORIGINS` | Allowed CORS origins | ["*"] |
## Project Structure
```
backend/
├── api/ # API routes (v1)
│ └── v1/ # Version 1 API
├── core/ # Core functionality
├── db/ # Database configuration
│ └── session.py # Session management
├── models/ # SQLAlchemy models
│ ├── article.py
│ ├── author.py
│ └── category.py
├── schemas/ # Pydantic schemas
│ ├── article.py
│ ├── author.py
│ └── category.py
├── tests/ # Unit tests
│ ├── conftest.py
│ ├── test_health.py
│ ├── test_version.py
│ └── test_models.py
├── main.py # FastAPI application
├── config.py # Configuration settings
├── requirements.txt # Python dependencies
├── Dockerfile # Container configuration
├── pytest.ini # Pytest configuration
└── README.md # This file
```
## Error Handling
The API returns standardized error responses:
### Validation Errors (422)
```json
{
"detail": "Validation error",
"message": "..."
}
```
### Internal Server Errors (500)
```json
{
"detail": "Internal server error"
}
```
## Development Notes
- Database uses SQLite with file-based storage
- Foreign key relationships are enforced
- Pydantic schemas provide request/response validation
- Docker Compose enables easy local development setup
## License
See parent directory LICENSE file.
View File
Whitespace-only changes.
+33
View File
@@ -0,0 +1,33 @@
"""
Backend configuration settings for Newzy application.
"""
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
"""Application settings."""
model_config = SettingsConfigDict(
env_file=".env",
env_file_encoding="utf-8",
case_sensitive=False,
)
# Application
APP_NAME: str = "Newzy"
APP_VERSION: str = "0.1.0"
DEBUG: bool = False
# Database
DATABASE_URL: str = "sqlite:///./data/db/newzy.db"
DATABASE_DIR: str = "./data/db"
# CORS
CORS_ORIGINS: list[str] = ["*"]
class Config:
case_sensitive = False
settings = Settings()
View File
Whitespace-only changes.
View File
Whitespace-only changes.
+26
View File
@@ -0,0 +1,26 @@
"""
Database session management for Newzy application.
"""
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, declarative_base
from config import settings
engine = create_engine(
settings.DATABASE_URL,
connect_args={"check_same_thread": False} if "sqlite" in settings.DATABASE_URL else {},
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
def get_db():
"""Dependency for injecting database sessions."""
db = SessionLocal()
try:
yield db
finally:
db.close()
+84
View File
@@ -0,0 +1,84 @@
"""
Main FastAPI application for Newzy news application.
"""
from contextlib import asynccontextmanager
from fastapi import FastAPI, HTTPException, status
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from pydantic import ValidationError
from config import settings
from db.session import engine, Base
from models.article import Article
from models.author import Author
from models.category import Category
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Application lifespan event handlers."""
# On startup - create database tables
Base.metadata.create_all(bind=engine)
yield
# On shutdown - cleanup if needed
app = FastAPI(
title=settings.APP_NAME,
version=settings.APP_VERSION,
description="Newzy News Application Backend API",
lifespan=lifespan,
)
# Exception handlers
@app.exception_handler(ValidationError)
async def validation_exception_handler(request, exc):
"""Handle Pydantic validation errors."""
return JSONResponse(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
content={"detail": "Validation error", "message": str(exc)},
)
@app.exception_handler(Exception)
async def general_exception_handler(request, exc):
"""Handle unhandled exceptions."""
return JSONResponse(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
content={"detail": "Internal server error"},
)
# Health check endpoint
@app.get("/health", tags=["Health"])
async def health_check():
"""Check if the application is running."""
return {"status": "healthy"}
# Version endpoint
@app.get("/api/v1/version", tags=["Info"])
async def get_version():
"""Get application version information."""
return {
"version": settings.APP_VERSION,
"application": settings.APP_NAME,
}
# Placeholder routes for future implementation
# (Models are defined but API endpoints will be added in subsequent milestones)
if __name__ == "__main__":
import uvicorn
uvicorn.run(
"main:app",
host="0.0.0.0",
port=8000,
reload=settings.DEBUG,
)
+9
View File
@@ -0,0 +1,9 @@
"""
Database models for Newzy application.
"""
from .article import Article
from .author import Author
from .category import Category
__all__ = ["Article", "Author", "Category"]
+27
View File
@@ -0,0 +1,27 @@
"""
Article model for Newzy application.
"""
from datetime import datetime
from sqlalchemy import Boolean, DateTime, ForeignKey, Integer, String, Text
from sqlalchemy.orm import Mapped, mapped_column, relationship
from db.session import Base
class Article(Base):
"""Represents a news article."""
__tablename__ = "articles"
id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)
title: Mapped[str] = mapped_column(String(200), unique=True, nullable=False)
content: Mapped[str] = mapped_column(Text, nullable=False)
author_id: Mapped[int] = mapped_column(ForeignKey("authors.id"), nullable=False)
category_id: Mapped[int] = mapped_column(ForeignKey("categories.id"), nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow)
published: Mapped[bool] = mapped_column(Boolean, default=False)
# Relationships
author: Mapped["Author"] = relationship("Author", back_populates="articles")
category: Mapped["Category"] = relationship("Category", back_populates="articles")
+23
View File
@@ -0,0 +1,23 @@
"""
Author model for Newzy application.
"""
from datetime import datetime
from sqlalchemy import ForeignKey, Integer, String, Text
from sqlalchemy.orm import Mapped, mapped_column, relationship
from db.session import Base
class Author(Base):
"""Represents an article author."""
__tablename__ = "authors"
id: Mapped[int] = mapped_column(Integer, primary_key=True, index=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)
# Relationships
articles: Mapped[list["Article"]] = relationship("Article", back_populates="author")
+21
View File
@@ -0,0 +1,21 @@
"""
Category model for Newzy application.
"""
from sqlalchemy import ForeignKey, Integer, String, Text
from sqlalchemy.orm import Mapped, mapped_column, relationship
from db.session import Base
class Category(Base):
"""Represents a content category."""
__tablename__ = "categories"
id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)
name: Mapped[str] = mapped_column(String(100), unique=True, nullable=False)
slug: Mapped[str] = mapped_column(String(100), unique=True, nullable=False)
# Relationships
articles: Mapped[list["Article"]] = relationship("Article", back_populates="category")
+8
View File
@@ -0,0 +1,8 @@
[pytest]
testpaths = tests
python_files = test_*.py
python_classes = Test*
python_functions = test_*
asyncio_mode = auto
addopts = -v --cov=. --cov-report=term-missing --cov-config=pytest.ini
filterwarnings = ignore::DeprecationWarning
+11
View File
@@ -0,0 +1,11 @@
# Backend dependencies for Newzy application
fastapi>=0.104.0
uvicorn[standard]>=0.24.0
sqlalchemy>=2.0.0
pydantic>=2.5.0
pydantic-settings>=2.1.0
python-multipart>=0.0.6
# Testing dependencies
pytest>=7.4.0
pytest-asyncio>=0.23.0
pytest-cov>=4.1.0
+19
View File
@@ -0,0 +1,19 @@
"""
Pydantic schemas for Newzy application.
"""
from .article import ArticleCreate, ArticleResponse, ArticleUpdate
from .author import AuthorCreate, AuthorResponse, AuthorUpdate
from .category import CategoryCreate, CategoryResponse, CategoryUpdate
__all__ = [
"ArticleCreate",
"ArticleResponse",
"ArticleUpdate",
"AuthorCreate",
"AuthorResponse",
"AuthorUpdate",
"CategoryCreate",
"CategoryResponse",
"CategoryUpdate",
]
+42
View File
@@ -0,0 +1,42 @@
"""
Pydantic schemas for Article model.
"""
from datetime import datetime
from typing import Optional
from pydantic import BaseModel, Field
class ArticleBase(BaseModel):
"""Base article schema."""
title: str = Field(..., min_length=1, max_length=200)
content: str = Field(..., min_length=1)
class ArticleCreate(ArticleBase):
"""Schema for creating a new article."""
author_id: int = Field(..., ge=1)
category_id: int = Field(..., ge=1)
class ArticleUpdate(BaseModel):
"""Schema for updating an article."""
title: Optional[str] = Field(None, min_length=1, max_length=200)
content: Optional[str] = Field(None, min_length=1)
published: Optional[bool] = None
class ArticleResponse(ArticleBase):
"""Schema for article response."""
id: int
author_id: int
category_id: int
created_at: datetime
published: bool
class Config:
from_attributes = True
+37
View File
@@ -0,0 +1,37 @@
"""
Pydantic schemas for Author model.
"""
from typing import Optional
from pydantic import BaseModel, EmailStr, Field
class AuthorBase(BaseModel):
"""Base author schema."""
name: str = Field(..., min_length=1, max_length=100)
email: EmailStr
bio: Optional[str] = Field(None, max_length=1000)
class AuthorCreate(AuthorBase):
"""Schema for creating a new author."""
pass
class AuthorUpdate(BaseModel):
"""Schema for updating an author."""
name: Optional[str] = Field(None, min_length=1, max_length=100)
email: Optional[EmailStr] = None
bio: Optional[str] = Field(None, max_length=1000)
class AuthorResponse(AuthorBase):
"""Schema for author response."""
id: int
class Config:
from_attributes = True
+35
View File
@@ -0,0 +1,35 @@
"""
Pydantic schemas for Category model.
"""
from typing import Optional
from pydantic import BaseModel, Field
class CategoryBase(BaseModel):
"""Base category schema."""
name: str = Field(..., min_length=1, max_length=100)
slug: str = Field(..., min_length=1, max_length=100)
class CategoryCreate(CategoryBase):
"""Schema for creating a new category."""
pass
class CategoryUpdate(BaseModel):
"""Schema for updating a category."""
name: Optional[str] = Field(None, min_length=1, max_length=100)
slug: Optional[str] = Field(None, min_length=1, max_length=100)
class CategoryResponse(CategoryBase):
"""Schema for category response."""
id: int
class Config:
from_attributes = True
+71
View File
@@ -0,0 +1,71 @@
"""
Pytest fixtures and configuration for Newzy tests.
"""
import pytest
from sqlalchemy import text
from config import settings
@pytest.fixture(scope="session")
def test_db_url():
"""Database URL for testing."""
return "sqlite:///./test_newzy.db"
@pytest.fixture(scope="function")
def db_engine(test_db_url):
"""Create an engine for the test database."""
from sqlalchemy import create_engine
engine = create_engine(
test_db_url,
connect_args={"check_same_thread": False},
)
return engine
@pytest.fixture(scope="function")
def db_session(db_engine):
"""Create a database session for testing."""
from sqlalchemy.orm import sessionmaker
SessionLocal = sessionmaker(bind=db_engine)
session = SessionLocal()
try:
yield session
finally:
session.close()
@pytest.fixture(scope="function")
def test_db(db_engine, db_session):
"""Setup and teardown for database tables in tests."""
from db.session import Base, engine as app_engine
from models.article import Article
from models.author import Author
from models.category import Category
# Create tables
Base.metadata.create_all(bind=db_engine)
# Clean up old test tables if any
for table in Base.metadata.sorted_tables:
db_session.execute(text(f"DELETE FROM {table.name}"))
db_session.commit()
yield db_session
# Cleanup after test
Base.metadata.drop_all(bind=db_engine)
@pytest.fixture
def create_db():
"""Create database tables."""
from db.session import Base, engine as app_engine
Base.metadata.create_all(bind=engine)
return lambda: Base.metadata.drop_all(bind=engine)
+52
View File
@@ -0,0 +1,52 @@
"""
Test health and version endpoints.
"""
import pytest
from fastapi.testclient import TestClient
from main import app
@pytest.fixture
def client():
"""Create test client."""
return TestClient(app)
class TestHealthEndpoint:
"""Tests for the /health endpoint."""
def test_health_returns_200(self, client):
"""Test that health check returns 200 OK."""
response = client.get("/health")
assert response.status_code == 200
def test_health_response_structure(self, client):
"""Test health response contains expected JSON structure."""
response = client.get("/health")
assert response.json()["status"] == "healthy"
def test_api_v1_health_exists(self, client):
"""Test alternative /api/v1/health path works."""
# Note: This endpoint is not yet implemented - placeholder test
response = client.get("/api/v1/health")
assert response.status_code == 200
class TestVersionEndpoint:
"""Tests for the /api/v1/version endpoint."""
def test_version_returns_200(self, client):
"""Test that version endpoint returns 200 OK."""
response = client.get("/api/v1/version")
assert response.status_code == 200
def test_version_response_format(self, client):
"""Test version response format validation."""
response = client.get("/api/v1/version")
data = response.json()
assert "version" in data
assert "application" in data
# Version should be in format like v0.1.0
assert isinstance(data["version"], str)
+151
View File
@@ -0,0 +1,151 @@
"""
Test database models and basic operations.
"""
import pytest
from sqlalchemy import inspect, text
from datetime import datetime
@pytest.fixture
def test_db():
"""Database session for model tests."""
yield None # Will be provided by conftest.py
class TestAuthorModel:
"""Tests for the Author model."""
def test_author_creation(self, db_session):
"""Test Author model creation with required fields."""
from models.author import Author
author = Author(
name="John Doe",
email="john@example.com",
bio="A test author"
)
assert author.id is None # ID assigned after commit
def test_author_unique_constraints(self, db_session):
"""Test that authors have unique name and email."""
from models.author import Author
# Create first author
author1 = Author(name="Jane Doe", email="jane@example.com")
db_session.add(author1)
db_session.commit()
# Try to create duplicate
try:
author2 = Author(name="Jane Doe", email="newemail@example.com")
db_session.add(author2)
db_session.commit()
# Should raise IntegrityError
pytest.fail("Expected IntegrityError for duplicate name")
except Exception as e:
assert "IntegrityError" in str(type(e).__name__) or "foreign_key" in str(type(e).__name__).lower()
def test_author_relationship(self, db_session):
"""Test author has articles relationship."""
from models.author import Author
author = Author(name="Test Author", email="test@example.com")
assert hasattr(author, "articles")
assert author.articles == [] # Initially empty
class TestCategoryModel:
"""Tests for the Category model."""
def test_category_creation(self, db_session):
"""Test Category model creation."""
from models.category import Category
category = Category(name="Technology", slug="technology")
assert category.id is None # ID assigned after commit
def test_category_unique_constraints(self, db_session):
"""Test that categories have unique name and slug."""
from models.category import Category
category1 = Category(name="News", slug="news")
db_session.add(category1)
db_session.commit()
# Try duplicate slug
try:
category2 = Category(name="Sports", slug="news") # Same slug as news
db_session.add(category2)
db_session.commit()
pytest.fail("Expected IntegrityError for duplicate slug")
except Exception:
pass # Expected
class TestArticleModel:
"""Tests for the Article model."""
def test_article_creation(self, db_session):
"""Test Article model creation with required fields."""
from models.author import Author
from models.category import Category
from models.article import Article
author = Author(name="Author", email="author@example.com")
category = Category(name="Category", slug="category")
db_session.add_all([author, category])
db_session.commit()
article = Article(
title="Test Article",
content="This is test content",
author_id=author.id,
category_id=category.id,
published=True
)
assert article.title == "Test Article"
def test_article_default_published(self, db_session):
"""Test that articles default to unpublished."""
from models.author import Author
from models.category import Category
from models.article import Article
author = Author(name="Author", email="author@example.com")
category = Category(name="Category", slug="category")
db_session.add_all([author, category])
db_session.commit()
article = Article(
title="Test Article",
content="Content",
author_id=author.id,
category_id=category.id
# published not specified - should default to False
)
assert article.published is False
class TestDatabaseSetup:
"""Tests for database initialization."""
def test_tables_exist(self, db_engine):
"""Test that all required tables are created."""
inspector = inspect(db_engine)
table_names = [t["name"] for t in inspector.get_table_names()]
assert "authors" in table_names
assert "categories" in table_names
assert "articles" in table_names
def test_foreign_keys_exist(self, db_session):
"""Test that foreign key relationships are defined."""
from models.article import Article
inspector = inspect(db_engine)
article_constraints = inspector.get_table_constraints("articles")
constraint_names = [c["name"] for c in article_constraints]
assert any("author_id" in str(c) for c in article_constraints)
assert any("category_id" in str(c) for c in article_constraints)
+40
View File
@@ -0,0 +1,40 @@
"""
Test version endpoint behavior.
"""
import pytest
from fastapi.testclient import TestClient
@pytest.fixture
def client():
"""Create test client."""
from main import app
return TestClient(app)
class TestVersionEndpoint:
"""Tests for the /api/v1/version endpoint."""
def test_version_endpoint_exists(self, client):
"""Test that version endpoint exists and is accessible."""
response = client.get("/api/v1/version")
assert response.status_code == 200
def test_version_format(self, client):
"""Test version returns valid version string."""
response = client.get("/api/v1/version")
data = response.json()
# Check structure
assert "version" in data
assert "application" in data
# Check version format (vX.Y.Z)
version = data["version"]
assert isinstance(version, str)
assert version.startswith("v")
if __name__ == "__main__":
pytest.main([__file__, "-v"])