diff --git a/README.md b/README.md index e8acfba..e78c79a 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,139 @@ -# FastAPI Application +# Generic REST API Service -This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform. +A robust and scalable REST API service built with FastAPI and SQLite. + +## Features + +- **Modern FastAPI Framework**: Fully typed and async-ready API framework +- **SQLAlchemy ORM**: Object-relational mapping for database interactions +- **Alembic Migrations**: Automated database schema migrations +- **Pydantic Models**: Request and response validation +- **Dependency Injection**: Clean, modular code structure +- **OpenAPI Documentation**: Auto-generated, interactive API docs +- **Health Check Endpoint**: API status monitoring +- **User Authentication**: Basic auth implementation + +## Project Structure + +``` +. +├── alembic.ini # Alembic configuration +├── app # Main application package +│ ├── api # API endpoints +│ │ ├── dependencies # FastAPI dependencies +│ │ └── v1 # API version 1 +│ │ ├── api.py # API router +│ │ └── endpoints # API endpoint modules +│ ├── core # Core application code +│ │ ├── app.py # FastAPI application factory +│ │ ├── config.py # Application configuration +│ │ └── security.py # Security utilities +│ ├── crud # CRUD operations +│ ├── db # Database utilities +│ │ └── session.py # Database session management +│ ├── models # SQLAlchemy models +│ └── schemas # Pydantic schemas +├── main.py # Application entry point +├── migrations # Alembic migrations +│ ├── env.py # Alembic environment +│ ├── script.py.mako # Alembic script template +│ └── versions # Migration versions +└── requirements.txt # Project dependencies +``` + +## Getting Started + +### Prerequisites + +- Python 3.8 or higher +- pip (Python package manager) + +### Installation + +1. Clone the repository: + ``` + git clone https://github.com/yourusername/genericrestapiservice.git + cd genericrestapiservice + ``` + +2. Create a virtual environment (optional but recommended): + ``` + python -m venv venv + source venv/bin/activate # On Windows: venv\Scripts\activate + ``` + +3. Install dependencies: + ``` + pip install -r requirements.txt + ``` + +4. Run database migrations: + ``` + alembic upgrade head + ``` + +5. Start the development server: + ``` + uvicorn main:app --reload + ``` + +The API will be available at http://localhost:8000. + +### API Documentation + +Once the application is running, you can access: + +- Interactive API documentation: http://localhost:8000/docs +- Alternative API documentation: http://localhost:8000/redoc + +## API Endpoints + +### Authentication + +- `POST /api/v1/auth/login` - Get access token +- `GET /api/v1/auth/me` - Get current user info + +### Users + +- `GET /api/v1/users/` - List all users (admin only) +- `POST /api/v1/users/` - Create a new user +- `GET /api/v1/users/{user_id}` - Get user details +- `PUT /api/v1/users/{user_id}` - Update user (admin only) +- `DELETE /api/v1/users/{user_id}` - Delete user (admin only) + +### Items + +- `GET /api/v1/items/` - List items (filtered by user) +- `POST /api/v1/items/` - Create a new item +- `GET /api/v1/items/{id}` - Get item details +- `PUT /api/v1/items/{id}` - Update item +- `DELETE /api/v1/items/{id}` - Delete item + +### Health Check + +- `GET /health` - API health status +- `GET /api/v1/health` - API health status (versioned) + +## Development + +### Adding New Models + +1. Define SQLAlchemy model in `app/models/` +2. Define Pydantic schemas in `app/schemas/` +3. Create CRUD operations in `app/crud/` +4. Create a new migration with Alembic: + ``` + alembic revision --autogenerate -m "Add new model" + ``` +5. Create API endpoints in `app/api/v1/endpoints/` +6. Register endpoints in `app/api/v1/api.py` + +### Running Tests + +``` +pytest +``` + +## License + +This project is licensed under the MIT License - see the LICENSE file for details. \ No newline at end of file diff --git a/alembic.ini b/alembic.ini new file mode 100644 index 0000000..bb9c6e0 --- /dev/null +++ b/alembic.ini @@ -0,0 +1,85 @@ +# A generic, single database configuration. + +[alembic] +# path to migration scripts +script_location = migrations + +# template used to generate migration files +# file_template = %%(rev)s_%%(slug)s + +# timezone to use when rendering the date +# within the migration file as well as the filename. +# string value is passed to dateutil.tz.gettz() +# leave blank for localtime +# timezone = + +# max length of characters to apply to the +# "slug" field +# truncate_slug_length = 40 + +# set to 'true' to run the environment during +# the 'revision' command, regardless of autogenerate +# revision_environment = false + +# set to 'true' to allow .pyc and .pyo files without +# a source .py file to be detected as revisions in the +# versions/ directory +# sourceless = false + +# version location specification; this defaults +# to migrations/versions. When using multiple version +# directories, initial revisions must be specified with --version-path +# version_locations = %(here)s/bar %(here)s/bat migrations/versions + +# the output encoding used when revision files +# are written from script.py.mako +# output_encoding = utf-8 + +# SQLite database URL - using absolute path as required +sqlalchemy.url = sqlite:////app/storage/db/db.sqlite + +[post_write_hooks] +# post_write_hooks defines scripts or Python functions that are run +# on newly generated revision scripts. See the documentation for further +# detail and examples + +# format using "black" - use the console_scripts runner, against the "black" entrypoint +# hooks=black +# black.type=console_scripts +# black.entrypoint=black +# black.options=-l 79 + +# Logging configuration +[loggers] +keys = root,sqlalchemy,alembic + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARN +handlers = console +qualname = + +[logger_sqlalchemy] +level = WARN +handlers = +qualname = sqlalchemy.engine + +[logger_alembic] +level = INFO +handlers = +qualname = alembic + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S \ No newline at end of file diff --git a/app/__init__.py b/app/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/api/__init__.py b/app/api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/api/dependencies/__init__.py b/app/api/dependencies/__init__.py new file mode 100644 index 0000000..2ccaa4a --- /dev/null +++ b/app/api/dependencies/__init__.py @@ -0,0 +1,14 @@ +from app.api.dependencies.db import get_db +from app.api.dependencies.users import ( + get_current_active_superuser, + get_current_active_user, + get_current_user, +) + +# Make dependencies available at the package level +__all__ = [ + "get_db", + "get_current_user", + "get_current_active_user", + "get_current_active_superuser", +] \ No newline at end of file diff --git a/app/api/dependencies/db.py b/app/api/dependencies/db.py new file mode 100644 index 0000000..b740e98 --- /dev/null +++ b/app/api/dependencies/db.py @@ -0,0 +1,4 @@ +from app.db.session import get_db + +# Re-export the get_db dependency +__all__ = ["get_db"] \ No newline at end of file diff --git a/app/api/dependencies/users.py b/app/api/dependencies/users.py new file mode 100644 index 0000000..cb4c375 --- /dev/null +++ b/app/api/dependencies/users.py @@ -0,0 +1,61 @@ +from typing import Annotated + +from fastapi import Depends, HTTPException, status +from fastapi.security import OAuth2PasswordBearer +from sqlalchemy.orm import Session + +from app.api.dependencies.db import get_db +from app.crud import user as user_crud +from app.models.user import User + +# This is just a placeholder. In a real application, you would use a proper auth system. +# For demonstration purposes, we'll use a simple approach +oauth2_scheme = OAuth2PasswordBearer(tokenUrl="api/v1/auth/login") + + +def get_current_user( + db: Annotated[Session, Depends(get_db)], + token: Annotated[str, Depends(oauth2_scheme)] +) -> User: + """ + Get the current authenticated user. + This is a simplified implementation - in a real app, you would validate JWT tokens. + """ + credentials_exception = HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Could not validate credentials", + headers={"WWW-Authenticate": "Bearer"}, + ) + + # In a real app, you would decode and validate the JWT token + # For this demo, we'll just fetch the first user from the database + # This is NOT secure and should NOT be used in production + user = db.query(User).first() + if user is None: + raise credentials_exception + + return user + + +def get_current_active_user( + current_user: Annotated[User, Depends(get_current_user)] +) -> User: + """ + Get the current active user. + """ + if not user_crud.is_active(current_user): + raise HTTPException(status_code=400, detail="Inactive user") + return current_user + + +def get_current_active_superuser( + current_user: Annotated[User, Depends(get_current_user)] +) -> User: + """ + Get the current active superuser. + """ + if not user_crud.is_superuser(current_user): + raise HTTPException( + status_code=403, detail="The user doesn't have enough privileges" + ) + return current_user \ No newline at end of file diff --git a/app/api/v1/__init__.py b/app/api/v1/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/api/v1/api.py b/app/api/v1/api.py new file mode 100644 index 0000000..ef6cc3e --- /dev/null +++ b/app/api/v1/api.py @@ -0,0 +1,11 @@ +from fastapi import APIRouter + +from app.api.v1.endpoints import auth, health, items, users + +api_router = APIRouter() + +# Include routers for different endpoints +api_router.include_router(auth.router, prefix="/auth", tags=["auth"]) +api_router.include_router(users.router, prefix="/users", tags=["users"]) +api_router.include_router(items.router, prefix="/items", tags=["items"]) +api_router.include_router(health.router, prefix="/health", tags=["health"]) \ No newline at end of file diff --git a/app/api/v1/endpoints/__init__.py b/app/api/v1/endpoints/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/api/v1/endpoints/auth.py b/app/api/v1/endpoints/auth.py new file mode 100644 index 0000000..4c5e9c8 --- /dev/null +++ b/app/api/v1/endpoints/auth.py @@ -0,0 +1,55 @@ +from typing import Annotated, Any + +from fastapi import APIRouter, Depends, HTTPException, status +from fastapi.security import OAuth2PasswordRequestForm +from sqlalchemy.orm import Session + +from app.api.dependencies import get_current_user, get_db +from app.core.security import generate_token +from app.crud import user +from app.models.user import User +from app.schemas.token import Token + +router = APIRouter() + + +@router.post("/login", response_model=Token) +def login_access_token( + db: Annotated[Session, Depends(get_db)], + form_data: Annotated[OAuth2PasswordRequestForm, Depends()], +) -> Any: + """ + OAuth2 compatible token login, get an access token for future requests. + """ + authenticated_user = user.authenticate( + db, email=form_data.username, password=form_data.password + ) + if not authenticated_user: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Incorrect email or password", + headers={"WWW-Authenticate": "Bearer"}, + ) + if not user.is_active(authenticated_user): + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, detail="Inactive user" + ) + + # In a real app, you would generate a proper JWT token + # For this demo, we'll just generate a random token + access_token = generate_token() + + return { + "access_token": access_token, + "token_type": "bearer", + } + + +@router.get("/me", response_model=Any) +def read_users_me( + current_user: Annotated[User, Depends(get_current_user)], +) -> Any: + """ + Get current user. + """ + return current_user \ No newline at end of file diff --git a/app/api/v1/endpoints/health.py b/app/api/v1/endpoints/health.py new file mode 100644 index 0000000..b29a09c --- /dev/null +++ b/app/api/v1/endpoints/health.py @@ -0,0 +1,13 @@ +from typing import Dict + +from fastapi import APIRouter + +router = APIRouter() + + +@router.get("/", response_model=Dict[str, str]) +async def health() -> Dict[str, str]: + """ + Health check endpoint to verify the API is running. + """ + return {"status": "healthy"} \ No newline at end of file diff --git a/app/api/v1/endpoints/items.py b/app/api/v1/endpoints/items.py new file mode 100644 index 0000000..4fd6a01 --- /dev/null +++ b/app/api/v1/endpoints/items.py @@ -0,0 +1,99 @@ +from typing import Annotated, Any, List + +from fastapi import APIRouter, Depends, HTTPException, status +from sqlalchemy.orm import Session + +from app.api.dependencies import get_current_active_user, get_db +from app.crud import item +from app.models.user import User +from app.schemas.item import Item as ItemSchema +from app.schemas.item import ItemCreate, ItemUpdate + +router = APIRouter() + + +@router.get("/", response_model=List[ItemSchema]) +def read_items( + db: Annotated[Session, Depends(get_db)], + current_user: Annotated[User, Depends(get_current_active_user)], + skip: int = 0, + limit: int = 100, +) -> Any: + """ + Retrieve items. + """ + if current_user.is_superuser: + items = item.get_multi(db, skip=skip, limit=limit) + else: + items = item.get_multi_by_owner( + db=db, owner_id=current_user.id, skip=skip, limit=limit + ) + return items + + +@router.post("/", response_model=ItemSchema, status_code=status.HTTP_201_CREATED) +def create_item( + *, + db: Annotated[Session, Depends(get_db)], + item_in: ItemCreate, + current_user: Annotated[User, Depends(get_current_active_user)], +) -> Any: + """ + Create new item. + """ + return item.create_with_owner(db=db, obj_in=item_in, owner_id=current_user.id) + + +@router.get("/{id}", response_model=ItemSchema) +def read_item( + *, + db: Annotated[Session, Depends(get_db)], + id: int, + current_user: Annotated[User, Depends(get_current_active_user)], +) -> Any: + """ + Get item by ID. + """ + db_item = item.get(db=db, id=id) + if db_item is None: + raise HTTPException(status_code=404, detail="Item not found") + if not current_user.is_superuser and (db_item.owner_id != current_user.id): + raise HTTPException(status_code=403, detail="Not enough permissions") + return db_item + + +@router.put("/{id}", response_model=ItemSchema) +def update_item( + *, + db: Annotated[Session, Depends(get_db)], + id: int, + item_in: ItemUpdate, + current_user: Annotated[User, Depends(get_current_active_user)], +) -> Any: + """ + Update an item. + """ + db_item = item.get(db=db, id=id) + if db_item is None: + raise HTTPException(status_code=404, detail="Item not found") + if not current_user.is_superuser and (db_item.owner_id != current_user.id): + raise HTTPException(status_code=403, detail="Not enough permissions") + return item.update(db=db, db_obj=db_item, obj_in=item_in) + + +@router.delete("/{id}", response_model=ItemSchema) +def delete_item( + *, + db: Annotated[Session, Depends(get_db)], + id: int, + current_user: Annotated[User, Depends(get_current_active_user)], +) -> Any: + """ + Delete an item. + """ + db_item = item.get(db=db, id=id) + if db_item is None: + raise HTTPException(status_code=404, detail="Item not found") + if not current_user.is_superuser and (db_item.owner_id != current_user.id): + raise HTTPException(status_code=403, detail="Not enough permissions") + return item.remove(db=db, id=id) \ No newline at end of file diff --git a/app/api/v1/endpoints/users.py b/app/api/v1/endpoints/users.py new file mode 100644 index 0000000..a779215 --- /dev/null +++ b/app/api/v1/endpoints/users.py @@ -0,0 +1,106 @@ +from typing import Annotated, Any, List + +from fastapi import APIRouter, Depends, HTTPException, status +from sqlalchemy.orm import Session + +from app.api.dependencies import get_current_active_superuser, get_db +from app.crud import user +from app.models.user import User +from app.schemas.user import User as UserSchema +from app.schemas.user import UserCreate, UserUpdate + +router = APIRouter() + + +@router.get("/", response_model=List[UserSchema]) +def read_users( + db: Annotated[Session, Depends(get_db)], + current_user: Annotated[User, Depends(get_current_active_superuser)], + skip: int = 0, + limit: int = 100, +) -> Any: + """ + Retrieve users. + """ + users = user.get_multi(db, skip=skip, limit=limit) + return users + + +@router.post("/", response_model=UserSchema, status_code=status.HTTP_201_CREATED) +def create_user( + *, + db: Annotated[Session, Depends(get_db)], + user_in: UserCreate, +) -> Any: + """ + Create new user. + """ + existing_user = user.get_by_email(db, email=user_in.email) + if existing_user: + raise HTTPException( + status_code=400, + detail="The user with this email already exists in the system.", + ) + existing_user = user.get_by_username(db, username=user_in.username) + if existing_user: + raise HTTPException( + status_code=400, + detail="The user with this username already exists in the system.", + ) + return user.create(db, obj_in=user_in) + + +@router.get("/{user_id}", response_model=UserSchema) +def read_user_by_id( + user_id: int, + db: Annotated[Session, Depends(get_db)], +) -> Any: + """ + Get a specific user by id. + """ + db_user = user.get(db, id=user_id) + if db_user is None: + raise HTTPException( + status_code=404, + detail="User not found", + ) + return db_user + + +@router.put("/{user_id}", response_model=UserSchema) +def update_user( + *, + db: Annotated[Session, Depends(get_db)], + user_id: int, + user_in: UserUpdate, + current_user: Annotated[User, Depends(get_current_active_superuser)], +) -> Any: + """ + Update a user. + """ + db_user = user.get(db, id=user_id) + if db_user is None: + raise HTTPException( + status_code=404, + detail="User not found", + ) + return user.update(db, db_obj=db_user, obj_in=user_in) + + +@router.delete("/{user_id}", response_model=UserSchema) +def delete_user( + *, + db: Annotated[Session, Depends(get_db)], + user_id: int, + current_user: Annotated[User, Depends(get_current_active_superuser)], +) -> Any: + """ + Delete a user. + """ + db_user = user.get(db, id=user_id) + if db_user is None: + raise HTTPException( + status_code=404, + detail="User not found", + ) + return user.remove(db, id=user_id) \ No newline at end of file diff --git a/app/core/__init__.py b/app/core/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/core/app.py b/app/core/app.py new file mode 100644 index 0000000..9f2ccf5 --- /dev/null +++ b/app/core/app.py @@ -0,0 +1,40 @@ +from fastapi import FastAPI +from fastapi.middleware.cors import CORSMiddleware + +from app.api.v1.api import api_router +from app.core.config import settings + + +def create_app() -> FastAPI: + """ + Create a FastAPI application instance with configured settings. + """ + app = FastAPI( + title=settings.PROJECT_NAME, + description=settings.PROJECT_DESCRIPTION, + version=settings.PROJECT_VERSION, + openapi_url=f"{settings.API_V1_STR}/openapi.json", + docs_url="/docs", + redoc_url="/redoc", + ) + + # Set up CORS middleware + app.add_middleware( + CORSMiddleware, + allow_origins=settings.CORS_ORIGINS, + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], + ) + + # Include API router + app.include_router(api_router, prefix=settings.API_V1_STR) + + @app.get("/health", tags=["Health"]) + async def health(): + """ + Health check endpoint to verify the API is running. + """ + return {"status": "healthy"} + + return app \ No newline at end of file diff --git a/app/core/config.py b/app/core/config.py new file mode 100644 index 0000000..cf7aabe --- /dev/null +++ b/app/core/config.py @@ -0,0 +1,34 @@ +from pathlib import Path +from typing import List + +from pydantic_settings import BaseSettings, SettingsConfigDict + + +class Settings(BaseSettings): + """Application settings.""" + + # API configuration + API_V1_STR: str = "/api/v1" + PROJECT_NAME: str = "Generic REST API Service" + PROJECT_DESCRIPTION: str = "A generic REST API service built with FastAPI" + PROJECT_VERSION: str = "0.1.0" + + # CORS configuration + CORS_ORIGINS: List[str] = ["*"] + + # Database configuration + DB_DIR: Path = Path("/app") / "storage" / "db" + SQLALCHEMY_DATABASE_URL: str = f"sqlite:///{DB_DIR}/db.sqlite" + + model_config = SettingsConfigDict( + env_file=".env", + env_file_encoding="utf-8", + case_sensitive=True + ) + + +# Create settings instance +settings = Settings() + +# Ensure database directory exists +settings.DB_DIR.mkdir(parents=True, exist_ok=True) \ No newline at end of file diff --git a/app/core/security.py b/app/core/security.py new file mode 100644 index 0000000..0b52f5d --- /dev/null +++ b/app/core/security.py @@ -0,0 +1,27 @@ +import secrets + +from passlib.context import CryptContext + +# Password hashing context +pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") + + +def verify_password(plain_password: str, hashed_password: str) -> bool: + """ + Verify a plain password against a hashed password. + """ + return pwd_context.verify(plain_password, hashed_password) + + +def get_password_hash(password: str) -> str: + """ + Hash a password using bcrypt. + """ + return pwd_context.hash(password) + + +def generate_token() -> str: + """ + Generate a secure random token. + """ + return secrets.token_urlsafe(32) \ No newline at end of file diff --git a/app/crud/__init__.py b/app/crud/__init__.py new file mode 100644 index 0000000..846201d --- /dev/null +++ b/app/crud/__init__.py @@ -0,0 +1,5 @@ +from app.crud.item import item +from app.crud.user import user + +# Make CRUD instances available at the package level +__all__ = ["user", "item"] \ No newline at end of file diff --git a/app/crud/base.py b/app/crud/base.py new file mode 100644 index 0000000..2b1190d --- /dev/null +++ b/app/crud/base.py @@ -0,0 +1,81 @@ +from typing import Any, Dict, Generic, List, Optional, Type, TypeVar, Union + +from fastapi.encoders import jsonable_encoder +from pydantic import BaseModel +from sqlalchemy.orm import Session + +from app.db.session import Base + +# Define generic types for SQLAlchemy models and Pydantic schemas +ModelType = TypeVar("ModelType", bound=Base) +CreateSchemaType = TypeVar("CreateSchemaType", bound=BaseModel) +UpdateSchemaType = TypeVar("UpdateSchemaType", bound=BaseModel) + + +class CRUDBase(Generic[ModelType, CreateSchemaType, UpdateSchemaType]): + """ + Base class for CRUD operations. + """ + + def __init__(self, model: Type[ModelType]): + """ + Initialize with SQLAlchemy model class. + """ + self.model = model + + def get(self, db: Session, id: Any) -> Optional[ModelType]: + """ + Get a record by ID. + """ + return db.query(self.model).filter(self.model.id == id).first() + + def get_multi( + self, db: Session, *, skip: int = 0, limit: int = 100 + ) -> List[ModelType]: + """ + Get multiple records with pagination. + """ + return db.query(self.model).offset(skip).limit(limit).all() + + def create(self, db: Session, *, obj_in: CreateSchemaType) -> ModelType: + """ + Create a new record. + """ + obj_in_data = jsonable_encoder(obj_in) + db_obj = self.model(**obj_in_data) + db.add(db_obj) + db.commit() + db.refresh(db_obj) + return db_obj + + def update( + self, + db: Session, + *, + db_obj: ModelType, + obj_in: Union[UpdateSchemaType, Dict[str, Any]] + ) -> ModelType: + """ + Update a record. + """ + obj_data = jsonable_encoder(db_obj) + if isinstance(obj_in, dict): + update_data = obj_in + else: + update_data = obj_in.model_dump(exclude_unset=True) + for field in obj_data: + if field in update_data: + setattr(db_obj, field, update_data[field]) + db.add(db_obj) + db.commit() + db.refresh(db_obj) + return db_obj + + def remove(self, db: Session, *, id: int) -> ModelType: + """ + Remove a record by ID. + """ + obj = db.query(self.model).get(id) + db.delete(obj) + db.commit() + return obj \ No newline at end of file diff --git a/app/crud/item.py b/app/crud/item.py new file mode 100644 index 0000000..65cd674 --- /dev/null +++ b/app/crud/item.py @@ -0,0 +1,47 @@ +from typing import List + +from sqlalchemy.orm import Session + +from app.crud.base import CRUDBase +from app.models.item import Item +from app.schemas.item import ItemCreate, ItemUpdate + + +class CRUDItem(CRUDBase[Item, ItemCreate, ItemUpdate]): + """ + CRUD operations for Item model. + """ + + def get_multi_by_owner( + self, db: Session, *, owner_id: int, skip: int = 0, limit: int = 100 + ) -> List[Item]: + """ + Get multiple items by owner ID with pagination. + """ + return ( + db.query(self.model) + .filter(Item.owner_id == owner_id) + .offset(skip) + .limit(limit) + .all() + ) + + def create_with_owner( + self, db: Session, *, obj_in: ItemCreate, owner_id: int + ) -> Item: + """ + Create a new item with owner ID. + """ + db_obj = Item( + title=obj_in.title, + description=obj_in.description, + owner_id=owner_id, + ) + db.add(db_obj) + db.commit() + db.refresh(db_obj) + return db_obj + + +# Create an instance for convenience +item = CRUDItem(Item) \ No newline at end of file diff --git a/app/crud/user.py b/app/crud/user.py new file mode 100644 index 0000000..c488b6c --- /dev/null +++ b/app/crud/user.py @@ -0,0 +1,88 @@ +from typing import Any, Dict, Optional, Union + +from sqlalchemy.orm import Session + +from app.core.security import get_password_hash, verify_password +from app.crud.base import CRUDBase +from app.models.user import User +from app.schemas.user import UserCreate, UserUpdate + + +class CRUDUser(CRUDBase[User, UserCreate, UserUpdate]): + """ + CRUD operations for User model. + """ + + def get_by_email(self, db: Session, *, email: str) -> Optional[User]: + """ + Get a user by email. + """ + return db.query(User).filter(User.email == email).first() + + def get_by_username(self, db: Session, *, username: str) -> Optional[User]: + """ + Get a user by username. + """ + return db.query(User).filter(User.username == username).first() + + def create(self, db: Session, *, obj_in: UserCreate) -> User: + """ + Create a new user with hashed password. + """ + db_obj = User( + email=obj_in.email, + username=obj_in.username, + hashed_password=get_password_hash(obj_in.password), + is_active=obj_in.is_active, + is_superuser=obj_in.is_superuser, + ) + db.add(db_obj) + db.commit() + db.refresh(db_obj) + return db_obj + + def update( + self, db: Session, *, db_obj: User, obj_in: Union[UserUpdate, Dict[str, Any]] + ) -> User: + """ + Update a user, handling password hashing if password is included. + """ + if isinstance(obj_in, dict): + update_data = obj_in + else: + update_data = obj_in.model_dump(exclude_unset=True) + + # Hash the password if it's in the update data + if update_data.get("password"): + hashed_password = get_password_hash(update_data["password"]) + del update_data["password"] + update_data["hashed_password"] = hashed_password + + return super().update(db, db_obj=db_obj, obj_in=update_data) + + def authenticate(self, db: Session, *, email: str, password: str) -> Optional[User]: + """ + Authenticate a user by email and password. + """ + user = self.get_by_email(db, email=email) + if not user: + return None + if not verify_password(password, user.hashed_password): + return None + return user + + def is_active(self, user: User) -> bool: + """ + Check if a user is active. + """ + return user.is_active + + def is_superuser(self, user: User) -> bool: + """ + Check if a user is a superuser. + """ + return user.is_superuser + + +# Create an instance for convenience +user = CRUDUser(User) \ No newline at end of file diff --git a/app/db/__init__.py b/app/db/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/db/session.py b/app/db/session.py new file mode 100644 index 0000000..9aab637 --- /dev/null +++ b/app/db/session.py @@ -0,0 +1,29 @@ +from sqlalchemy import create_engine +from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy.orm import sessionmaker + +from app.core.config import settings + +# Create SQLAlchemy engine +engine = create_engine( + settings.SQLALCHEMY_DATABASE_URL, + connect_args={"check_same_thread": False} # Needed for SQLite +) + +# Create sessionmaker +SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) + +# Create Base class for declarative models +Base = declarative_base() + + +def get_db(): + """ + Dependency function to get a DB session. + To be used in FastAPI dependency injection system. + """ + db = SessionLocal() + try: + yield db + finally: + db.close() \ No newline at end of file diff --git a/app/models/__init__.py b/app/models/__init__.py new file mode 100644 index 0000000..4efbafd --- /dev/null +++ b/app/models/__init__.py @@ -0,0 +1,5 @@ +from app.models.item import Item +from app.models.user import User + +# For Alembic autogenerate to detect models +__all__ = ["User", "Item"] \ No newline at end of file diff --git a/app/models/item.py b/app/models/item.py new file mode 100644 index 0000000..dd71de2 --- /dev/null +++ b/app/models/item.py @@ -0,0 +1,19 @@ +from sqlalchemy import Column, ForeignKey, Integer, String, Text +from sqlalchemy.orm import relationship + +from app.db.session import Base + + +class Item(Base): + """ + Item model for storing items data. + """ + __tablename__ = "items" + + id = Column(Integer, primary_key=True, index=True) + title = Column(String, index=True, nullable=False) + description = Column(Text, nullable=True) + owner_id = Column(Integer, ForeignKey("users.id"), nullable=False) + + # Relationship to user + owner = relationship("User", back_populates="items") \ No newline at end of file diff --git a/app/models/user.py b/app/models/user.py new file mode 100644 index 0000000..6f0e6b6 --- /dev/null +++ b/app/models/user.py @@ -0,0 +1,21 @@ +from sqlalchemy import Boolean, Column, Integer, String +from sqlalchemy.orm import relationship + +from app.db.session import Base + + +class User(Base): + """ + User model for storing user information. + """ + __tablename__ = "users" + + id = Column(Integer, primary_key=True, index=True) + email = Column(String, unique=True, index=True, nullable=False) + username = Column(String, unique=True, index=True, nullable=False) + hashed_password = Column(String, nullable=False) + is_active = Column(Boolean, default=True) + is_superuser = Column(Boolean, default=False) + + # Relationship to items + items = relationship("Item", back_populates="owner") \ No newline at end of file diff --git a/app/schemas/__init__.py b/app/schemas/__init__.py new file mode 100644 index 0000000..bcce1f3 --- /dev/null +++ b/app/schemas/__init__.py @@ -0,0 +1,10 @@ +from app.schemas.item import Item, ItemCreate, ItemInDB, ItemUpdate +from app.schemas.token import Token, TokenPayload +from app.schemas.user import User, UserCreate, UserInDB, UserUpdate + +# Make schemas available at the package level +__all__ = [ + "User", "UserCreate", "UserUpdate", "UserInDB", + "Item", "ItemCreate", "ItemUpdate", "ItemInDB", + "Token", "TokenPayload", +] \ No newline at end of file diff --git a/app/schemas/item.py b/app/schemas/item.py new file mode 100644 index 0000000..dd37ece --- /dev/null +++ b/app/schemas/item.py @@ -0,0 +1,38 @@ +from typing import Optional + +from pydantic import BaseModel, ConfigDict + + +class ItemBase(BaseModel): + """Base schema for Item.""" + title: str + description: Optional[str] = None + + +class ItemCreate(ItemBase): + """Schema for creating a new Item.""" + pass + + +class ItemUpdate(BaseModel): + """Schema for updating an Item.""" + title: Optional[str] = None + description: Optional[str] = None + + +class ItemInDBBase(ItemBase): + """Base schema for Item in DB.""" + id: int + owner_id: int + + model_config = ConfigDict(from_attributes=True) + + +class Item(ItemInDBBase): + """Schema for Item returned to the client.""" + pass + + +class ItemInDB(ItemInDBBase): + """Schema for Item in DB.""" + pass \ No newline at end of file diff --git a/app/schemas/token.py b/app/schemas/token.py new file mode 100644 index 0000000..9b013d8 --- /dev/null +++ b/app/schemas/token.py @@ -0,0 +1,14 @@ +from typing import Optional + +from pydantic import BaseModel + + +class Token(BaseModel): + """Schema for token response.""" + access_token: str + token_type: str + + +class TokenPayload(BaseModel): + """Schema for token payload.""" + sub: Optional[int] = None \ No newline at end of file diff --git a/app/schemas/user.py b/app/schemas/user.py new file mode 100644 index 0000000..fca15a5 --- /dev/null +++ b/app/schemas/user.py @@ -0,0 +1,42 @@ +from typing import Optional + +from pydantic import BaseModel, ConfigDict, EmailStr, Field + + +class UserBase(BaseModel): + """Base schema for User.""" + email: EmailStr + username: str + is_active: bool = True + is_superuser: bool = False + + +class UserCreate(UserBase): + """Schema for creating a new User.""" + password: str = Field(..., min_length=8) + + +class UserUpdate(BaseModel): + """Schema for updating a User.""" + email: Optional[EmailStr] = None + username: Optional[str] = None + password: Optional[str] = Field(None, min_length=8) + is_active: Optional[bool] = None + is_superuser: Optional[bool] = None + + +class UserInDBBase(UserBase): + """Base schema for User in DB.""" + id: int + + model_config = ConfigDict(from_attributes=True) + + +class User(UserInDBBase): + """Schema for User returned to the client.""" + pass + + +class UserInDB(UserInDBBase): + """Schema for User in DB with password hash.""" + hashed_password: str \ No newline at end of file diff --git a/main.py b/main.py new file mode 100644 index 0000000..60d2c01 --- /dev/null +++ b/main.py @@ -0,0 +1,8 @@ +import uvicorn + +from app.core.app import create_app + +app = create_app() + +if __name__ == "__main__": + uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True) \ No newline at end of file diff --git a/migrations/env.py b/migrations/env.py new file mode 100644 index 0000000..95a875a --- /dev/null +++ b/migrations/env.py @@ -0,0 +1,83 @@ +import sys +from logging.config import fileConfig +from pathlib import Path + +from alembic import context +from sqlalchemy import engine_from_config, pool + +# Add the parent directory to sys.path +sys.path.append(str(Path(__file__).parent.parent)) + +# Import the SQLAlchemy metadata object and Base +from app.db.session import Base +from app.models import Item, User # noqa: F401 + +# this is the Alembic Config object, which provides +# access to the values within the .ini file in use. +config = context.config + +# Interpret the config file for Python logging. +# This line sets up loggers basically. +fileConfig(config.config_file_name) + +# add your model's MetaData object here +# for 'autogenerate' support +target_metadata = Base.metadata + + +def run_migrations_offline(): + """Run migrations in 'offline' mode. + + This configures the context with just a URL + and not an Engine, though an Engine is acceptable + here as well. By skipping the Engine creation + we don't even need a DBAPI to be available. + + Calls to context.execute() here emit the given string to the + script output. + + """ + url = config.get_main_option("sqlalchemy.url") + context.configure( + url=url, + target_metadata=target_metadata, + literal_binds=True, + dialect_opts={"paramstyle": "named"}, + ) + + with context.begin_transaction(): + context.run_migrations() + + +def run_migrations_online(): + """Run migrations in 'online' mode. + + In this scenario we need to create an Engine + and associate a connection with the context. + + """ + connectable = engine_from_config( + config.get_section(config.config_ini_section), + prefix="sqlalchemy.", + poolclass=pool.NullPool, + ) + + with connectable.connect() as connection: + # Check if we're working with SQLite + is_sqlite = connection.dialect.name == "sqlite" + + context.configure( + connection=connection, + target_metadata=target_metadata, + # Use batch mode for SQLite + render_as_batch=is_sqlite, + ) + + with context.begin_transaction(): + context.run_migrations() + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() \ No newline at end of file diff --git a/migrations/script.py.mako b/migrations/script.py.mako new file mode 100644 index 0000000..1e4564e --- /dev/null +++ b/migrations/script.py.mako @@ -0,0 +1,24 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision | comma,n} +Create Date: ${create_date} + +""" +from alembic import op +import sqlalchemy as sa +${imports if imports else ""} + +# revision identifiers, used by Alembic. +revision = ${repr(up_revision)} +down_revision = ${repr(down_revision)} +branch_labels = ${repr(branch_labels)} +depends_on = ${repr(depends_on)} + + +def upgrade(): + ${upgrades if upgrades else "pass"} + + +def downgrade(): + ${downgrades if downgrades else "pass"} \ No newline at end of file diff --git a/migrations/versions/__init__.py b/migrations/versions/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/migrations/versions/initial_migration.py b/migrations/versions/initial_migration.py new file mode 100644 index 0000000..8550deb --- /dev/null +++ b/migrations/versions/initial_migration.py @@ -0,0 +1,58 @@ +"""Initial migration + +Revision ID: 01_initial_migration +Revises: +Create Date: 2023-07-01 + +""" +import sqlalchemy as sa +from alembic import op + +# revision identifiers, used by Alembic. +revision = '01_initial_migration' +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade(): + # Create users table + op.create_table( + 'users', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('email', sa.String(), nullable=False), + sa.Column('username', sa.String(), nullable=False), + sa.Column('hashed_password', sa.String(), nullable=False), + sa.Column('is_active', sa.Boolean(), nullable=True), + sa.Column('is_superuser', sa.Boolean(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_users_email'), 'users', ['email'], unique=True) + op.create_index(op.f('ix_users_id'), 'users', ['id'], unique=False) + op.create_index(op.f('ix_users_username'), 'users', ['username'], unique=True) + + # Create items table + op.create_table( + 'items', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('title', sa.String(), nullable=False), + sa.Column('description', sa.Text(), nullable=True), + sa.Column('owner_id', sa.Integer(), nullable=False), + sa.ForeignKeyConstraint(['owner_id'], ['users.id'], ), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_items_id'), 'items', ['id'], unique=False) + op.create_index(op.f('ix_items_title'), 'items', ['title'], unique=False) + + +def downgrade(): + # Drop items table + op.drop_index(op.f('ix_items_title'), table_name='items') + op.drop_index(op.f('ix_items_id'), table_name='items') + op.drop_table('items') + + # Drop users table + op.drop_index(op.f('ix_users_username'), table_name='users') + op.drop_index(op.f('ix_users_id'), table_name='users') + op.drop_index(op.f('ix_users_email'), table_name='users') + op.drop_table('users') \ No newline at end of file diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..0fd41f5 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,35 @@ +[tool.ruff] +# Exclude a variety of commonly ignored directories. +exclude = [ + ".git", + ".ruff_cache", + "__pypackages__", + "dist", + "venv", + ".venv", + "env", +] + +# Same as Black. +line-length = 88 + +# Assume Python 3.8 +target-version = "py38" + +[tool.ruff.lint] +# Enable flake8-bugbear (`B`) rules. +select = ["E", "F", "B", "I"] + +# Allow unused variables when underscore-prefixed. +dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$" + +[tool.ruff.lint.mccabe] +# Unlike Flake8, default to a complexity level of 10. +max-complexity = 10 + +[tool.ruff.lint.isort] +known-third-party = ["fastapi", "pydantic", "sqlalchemy", "alembic"] + +[tool.ruff.lint.per-file-ignores] +# Ignore unused imports in __init__.py files +"__init__.py" = ["F401"] \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..113f94e --- /dev/null +++ b/requirements.txt @@ -0,0 +1,15 @@ +fastapi>=0.100.0 +uvicorn>=0.22.0 +pydantic>=2.0.0 +pydantic-settings>=2.0.0 +sqlalchemy>=2.0.0 +alembic>=1.11.0 +python-multipart>=0.0.6 +python-dotenv>=1.0.0 +email-validator>=2.0.0 +passlib>=1.7.4 +bcrypt>=4.0.1 +python-jose>=3.3.0 +ruff>=0.0.275 +httpx>=0.24.1 +pytest>=7.3.1 \ No newline at end of file