Create FastAPI Todo App with SQLite and CRUD functionality
This commit is contained in:
parent
a027bf32ac
commit
da0fe5a40e
109
README.md
109
README.md
@ -1,3 +1,108 @@
|
|||||||
# FastAPI Application
|
# FastAPI Todo App
|
||||||
|
|
||||||
This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform.
|
A simple Todo API built with FastAPI and SQLite.
|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
- Create, read, update, and delete Todo items
|
||||||
|
- RESTful API endpoints
|
||||||
|
- SQLite database with SQLAlchemy ORM
|
||||||
|
- Alembic migrations
|
||||||
|
- API documentation with Swagger UI and ReDoc
|
||||||
|
|
||||||
|
## Project Structure
|
||||||
|
|
||||||
|
```
|
||||||
|
simpletodoapp/
|
||||||
|
├── alembic/ # Database migrations
|
||||||
|
│ ├── versions/ # Migration scripts
|
||||||
|
│ ├── env.py # Migration environment
|
||||||
|
│ └── script.py.mako # Migration script template
|
||||||
|
├── app/ # Application package
|
||||||
|
│ ├── api/ # API endpoints
|
||||||
|
│ │ └── routers/ # API routers
|
||||||
|
│ │ ├── health.py # Health check endpoints
|
||||||
|
│ │ └── todos.py # Todo endpoints
|
||||||
|
│ ├── core/ # Core functionality
|
||||||
|
│ │ └── database.py # Database configuration
|
||||||
|
│ ├── models/ # SQLAlchemy models
|
||||||
|
│ │ └── todo.py # Todo model
|
||||||
|
│ ├── schemas/ # Pydantic schemas
|
||||||
|
│ │ └── todo.py # Todo schemas
|
||||||
|
│ └── services/ # Business logic
|
||||||
|
│ └── todo.py # Todo services
|
||||||
|
├── storage/ # Data storage directory
|
||||||
|
│ └── db/ # Database files
|
||||||
|
├── alembic.ini # Alembic configuration
|
||||||
|
├── main.py # Application entry point
|
||||||
|
├── pyproject.toml # Project configuration (Ruff)
|
||||||
|
└── requirements.txt # Python dependencies
|
||||||
|
```
|
||||||
|
|
||||||
|
## Getting Started
|
||||||
|
|
||||||
|
### Prerequisites
|
||||||
|
|
||||||
|
- Python 3.8 or higher
|
||||||
|
|
||||||
|
### Installation
|
||||||
|
|
||||||
|
1. Clone the repository
|
||||||
|
2. Install dependencies:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pip install -r requirements.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
3. Run the application:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
uvicorn main:app --reload
|
||||||
|
```
|
||||||
|
|
||||||
|
The API will be available at http://localhost:8000
|
||||||
|
|
||||||
|
### API Documentation
|
||||||
|
|
||||||
|
- Swagger UI: http://localhost:8000/docs
|
||||||
|
- ReDoc: http://localhost:8000/redoc
|
||||||
|
|
||||||
|
## API Endpoints
|
||||||
|
|
||||||
|
### Health Check
|
||||||
|
|
||||||
|
- `GET /health` - Check API health
|
||||||
|
|
||||||
|
### Todo Operations
|
||||||
|
|
||||||
|
- `GET /api/todos` - List all todos
|
||||||
|
- `GET /api/todos/{todo_id}` - Get a single todo
|
||||||
|
- `POST /api/todos` - Create a new todo
|
||||||
|
- `PUT /api/todos/{todo_id}` - Update a todo
|
||||||
|
- `DELETE /api/todos/{todo_id}` - Delete a todo
|
||||||
|
|
||||||
|
## Database Migrations
|
||||||
|
|
||||||
|
The application uses Alembic for database migrations. The initial migration is included to create the `todos` table.
|
||||||
|
|
||||||
|
To apply migrations:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
alembic upgrade head
|
||||||
|
```
|
||||||
|
|
||||||
|
## Development
|
||||||
|
|
||||||
|
### Linting
|
||||||
|
|
||||||
|
The project uses Ruff for linting:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
ruff check .
|
||||||
|
```
|
||||||
|
|
||||||
|
To automatically fix linting issues:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
ruff check --fix .
|
||||||
|
```
|
86
alembic.ini
Normal file
86
alembic.ini
Normal file
@ -0,0 +1,86 @@
|
|||||||
|
# A generic, single database configuration.
|
||||||
|
|
||||||
|
[alembic]
|
||||||
|
# path to migration scripts
|
||||||
|
script_location = alembic
|
||||||
|
|
||||||
|
# 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 alembic/versions. When using multiple version
|
||||||
|
# directories, initial revisions must be specified with --version-path
|
||||||
|
# version_locations = %(here)s/bar %(here)s/bat alembic/versions
|
||||||
|
|
||||||
|
# the output encoding used when revision files
|
||||||
|
# are written from script.py.mako
|
||||||
|
# output_encoding = utf-8
|
||||||
|
|
||||||
|
# SQLite URL example
|
||||||
|
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
|
78
alembic/env.py
Normal file
78
alembic/env.py
Normal file
@ -0,0 +1,78 @@
|
|||||||
|
"""
|
||||||
|
Alembic environment script for database migrations
|
||||||
|
"""
|
||||||
|
from logging.config import fileConfig
|
||||||
|
|
||||||
|
from alembic import context
|
||||||
|
from sqlalchemy import engine_from_config, pool
|
||||||
|
|
||||||
|
# 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.
|
||||||
|
if config.config_file_name is not None:
|
||||||
|
fileConfig(config.config_file_name)
|
||||||
|
|
||||||
|
# add your model's MetaData object here
|
||||||
|
# for 'autogenerate' support
|
||||||
|
from app.models import Todo # noqa
|
||||||
|
from app.core.database import Base # noqa
|
||||||
|
|
||||||
|
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:
|
||||||
|
is_sqlite = connection.dialect.name == 'sqlite'
|
||||||
|
context.configure(
|
||||||
|
connection=connection,
|
||||||
|
target_metadata=target_metadata,
|
||||||
|
render_as_batch=is_sqlite, # Key configuration for SQLite
|
||||||
|
)
|
||||||
|
|
||||||
|
with context.begin_transaction():
|
||||||
|
context.run_migrations()
|
||||||
|
|
||||||
|
|
||||||
|
if context.is_offline_mode():
|
||||||
|
run_migrations_offline()
|
||||||
|
else:
|
||||||
|
run_migrations_online()
|
24
alembic/script.py.mako
Normal file
24
alembic/script.py.mako
Normal file
@ -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"}
|
39
alembic/versions/initial_migration.py
Normal file
39
alembic/versions/initial_migration.py
Normal file
@ -0,0 +1,39 @@
|
|||||||
|
"""Create todos table
|
||||||
|
|
||||||
|
Revision ID: e6d3d15b6c3c
|
||||||
|
Revises:
|
||||||
|
Create Date: 2023-08-01 12:00:00.000000
|
||||||
|
|
||||||
|
"""
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = 'e6d3d15b6c3c'
|
||||||
|
down_revision = None
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
op.create_table(
|
||||||
|
'todos',
|
||||||
|
sa.Column('id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('title', sa.String(length=255), nullable=False),
|
||||||
|
sa.Column('description', sa.Text(), nullable=True),
|
||||||
|
sa.Column('completed', sa.Boolean(), default=False),
|
||||||
|
sa.Column('created_at', sa.DateTime(), default=sa.func.current_timestamp()),
|
||||||
|
sa.Column(
|
||||||
|
'updated_at',
|
||||||
|
sa.DateTime(),
|
||||||
|
default=sa.func.current_timestamp(),
|
||||||
|
onupdate=sa.func.current_timestamp(),
|
||||||
|
),
|
||||||
|
sa.PrimaryKeyConstraint('id')
|
||||||
|
)
|
||||||
|
op.create_index(op.f('ix_todos_id'), 'todos', ['id'], unique=False)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
op.drop_index(op.f('ix_todos_id'), table_name='todos')
|
||||||
|
op.drop_table('todos')
|
0
app/__init__.py
Normal file
0
app/__init__.py
Normal file
0
app/api/__init__.py
Normal file
0
app/api/__init__.py
Normal file
0
app/api/routers/__init__.py
Normal file
0
app/api/routers/__init__.py
Normal file
14
app/api/routers/health.py
Normal file
14
app/api/routers/health.py
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
"""
|
||||||
|
Health check endpoints
|
||||||
|
"""
|
||||||
|
from fastapi import APIRouter
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/health")
|
||||||
|
def health_check():
|
||||||
|
"""
|
||||||
|
Health check endpoint to verify the application is running
|
||||||
|
"""
|
||||||
|
return {"status": "ok"}
|
75
app/api/routers/todos.py
Normal file
75
app/api/routers/todos.py
Normal file
@ -0,0 +1,75 @@
|
|||||||
|
"""
|
||||||
|
Router for Todo CRUD operations
|
||||||
|
"""
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException, Response, status
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from app.core.database import get_db
|
||||||
|
from app.schemas.todo import Todo, TodoCreate, TodoUpdate
|
||||||
|
from app.services import todo as todo_service
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/todos", response_model=list[Todo])
|
||||||
|
def get_todos(
|
||||||
|
skip: int = 0, limit: int = 100, db: Session = Depends(get_db)
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Get all todos with pagination
|
||||||
|
"""
|
||||||
|
todos = todo_service.get_todos(db, skip=skip, limit=limit)
|
||||||
|
return todos
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/todos/{todo_id}", response_model=Todo)
|
||||||
|
def get_todo(todo_id: int, db: Session = Depends(get_db)):
|
||||||
|
"""
|
||||||
|
Get a single todo by ID
|
||||||
|
"""
|
||||||
|
db_todo = todo_service.get_todo(db, todo_id=todo_id)
|
||||||
|
if db_todo is None:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=404,
|
||||||
|
detail=f"Todo with ID {todo_id} not found"
|
||||||
|
)
|
||||||
|
return db_todo
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/todos", response_model=Todo, status_code=status.HTTP_201_CREATED)
|
||||||
|
def create_todo(todo: TodoCreate, db: Session = Depends(get_db)):
|
||||||
|
"""
|
||||||
|
Create a new todo
|
||||||
|
"""
|
||||||
|
return todo_service.create_todo(db=db, todo=todo)
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/todos/{todo_id}", response_model=Todo)
|
||||||
|
def update_todo(
|
||||||
|
todo_id: int, todo_update: TodoUpdate, db: Session = Depends(get_db)
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Update an existing todo
|
||||||
|
"""
|
||||||
|
db_todo = todo_service.update_todo(db, todo_id, todo_update)
|
||||||
|
if db_todo is None:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=404,
|
||||||
|
detail=f"Todo with ID {todo_id} not found"
|
||||||
|
)
|
||||||
|
return db_todo
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/todos/{todo_id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None)
|
||||||
|
def delete_todo(todo_id: int, db: Session = Depends(get_db)):
|
||||||
|
"""
|
||||||
|
Delete a todo
|
||||||
|
"""
|
||||||
|
success = todo_service.delete_todo(db, todo_id)
|
||||||
|
if not success:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=404,
|
||||||
|
detail=f"Todo with ID {todo_id} not found"
|
||||||
|
)
|
||||||
|
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
0
app/core/__init__.py
Normal file
0
app/core/__init__.py
Normal file
41
app/core/database.py
Normal file
41
app/core/database.py
Normal file
@ -0,0 +1,41 @@
|
|||||||
|
"""
|
||||||
|
Database configuration module
|
||||||
|
"""
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from sqlalchemy import create_engine
|
||||||
|
from sqlalchemy.ext.declarative import declarative_base
|
||||||
|
from sqlalchemy.orm import sessionmaker
|
||||||
|
|
||||||
|
# Create database directory if it doesn't exist
|
||||||
|
DB_DIR = Path("/app") / "storage" / "db"
|
||||||
|
DB_DIR.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
SQLALCHEMY_DATABASE_URL = f"sqlite:///{DB_DIR}/db.sqlite"
|
||||||
|
|
||||||
|
engine = create_engine(
|
||||||
|
SQLALCHEMY_DATABASE_URL,
|
||||||
|
connect_args={"check_same_thread": False}
|
||||||
|
)
|
||||||
|
|
||||||
|
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||||
|
|
||||||
|
Base = declarative_base()
|
||||||
|
|
||||||
|
|
||||||
|
def get_db():
|
||||||
|
"""
|
||||||
|
Dependency for getting a database session
|
||||||
|
"""
|
||||||
|
db = SessionLocal()
|
||||||
|
try:
|
||||||
|
yield db
|
||||||
|
finally:
|
||||||
|
db.close()
|
||||||
|
|
||||||
|
|
||||||
|
def create_db_and_tables():
|
||||||
|
"""
|
||||||
|
Create database tables from SQLAlchemy models
|
||||||
|
"""
|
||||||
|
Base.metadata.create_all(bind=engine)
|
6
app/models/__init__.py
Normal file
6
app/models/__init__.py
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
"""
|
||||||
|
Models package for SQLAlchemy database models
|
||||||
|
"""
|
||||||
|
from app.models.todo import Todo # noqa
|
||||||
|
|
||||||
|
__all__ = ["Todo"]
|
22
app/models/todo.py
Normal file
22
app/models/todo.py
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
"""
|
||||||
|
SQLAlchemy model for Todo items
|
||||||
|
"""
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from sqlalchemy import Boolean, Column, DateTime, Integer, String, Text
|
||||||
|
|
||||||
|
from app.core.database import Base
|
||||||
|
|
||||||
|
|
||||||
|
class Todo(Base):
|
||||||
|
"""
|
||||||
|
Todo model for storing task information
|
||||||
|
"""
|
||||||
|
__tablename__ = "todos"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
title = Column(String(255), nullable=False)
|
||||||
|
description = Column(Text, nullable=True)
|
||||||
|
completed = Column(Boolean, default=False)
|
||||||
|
created_at = Column(DateTime, default=datetime.utcnow)
|
||||||
|
updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
6
app/schemas/__init__.py
Normal file
6
app/schemas/__init__.py
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
"""
|
||||||
|
Schemas package for Pydantic models
|
||||||
|
"""
|
||||||
|
from app.schemas.todo import Todo, TodoCreate, TodoInDB, TodoUpdate # noqa
|
||||||
|
|
||||||
|
__all__ = ["Todo", "TodoCreate", "TodoUpdate", "TodoInDB"]
|
56
app/schemas/todo.py
Normal file
56
app/schemas/todo.py
Normal file
@ -0,0 +1,56 @@
|
|||||||
|
"""
|
||||||
|
Pydantic schemas for Todo
|
||||||
|
"""
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
|
|
||||||
|
class TodoBase(BaseModel):
|
||||||
|
"""
|
||||||
|
Base Todo schema with shared attributes
|
||||||
|
"""
|
||||||
|
title: str = Field(..., min_length=1, max_length=255, description="The title of the todo item")
|
||||||
|
description: str | None = Field(None, description="Optional detailed description of the todo item")
|
||||||
|
completed: bool = Field(False, description="Whether the todo item is completed")
|
||||||
|
|
||||||
|
|
||||||
|
class TodoCreate(TodoBase):
|
||||||
|
"""
|
||||||
|
Schema for creating a new Todo
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class TodoUpdate(BaseModel):
|
||||||
|
"""
|
||||||
|
Schema for updating an existing Todo
|
||||||
|
"""
|
||||||
|
title: str | None = Field(None, min_length=1, max_length=255, description="The title of the todo item")
|
||||||
|
description: str | None = Field(None, description="Optional detailed description of the todo item")
|
||||||
|
completed: bool | None = Field(None, description="Whether the todo item is completed")
|
||||||
|
|
||||||
|
|
||||||
|
class TodoInDB(TodoBase):
|
||||||
|
"""
|
||||||
|
Schema for Todo as stored in the database
|
||||||
|
"""
|
||||||
|
id: int
|
||||||
|
created_at: datetime
|
||||||
|
updated_at: datetime
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
"""
|
||||||
|
Pydantic configuration
|
||||||
|
"""
|
||||||
|
from_attributes = True
|
||||||
|
json_encoders = {
|
||||||
|
datetime: lambda v: v.isoformat()
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class Todo(TodoInDB):
|
||||||
|
"""
|
||||||
|
Schema for Todo response
|
||||||
|
"""
|
||||||
|
pass
|
4
app/services/__init__.py
Normal file
4
app/services/__init__.py
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
"""
|
||||||
|
Services package for business logic and database operations
|
||||||
|
"""
|
||||||
|
# Import services here when needed
|
66
app/services/todo.py
Normal file
66
app/services/todo.py
Normal file
@ -0,0 +1,66 @@
|
|||||||
|
"""
|
||||||
|
Service functions for Todo CRUD operations
|
||||||
|
"""
|
||||||
|
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from app.models.todo import Todo
|
||||||
|
from app.schemas.todo import TodoCreate, TodoUpdate
|
||||||
|
|
||||||
|
|
||||||
|
def get_todos(db: Session, skip: int = 0, limit: int = 100) -> list[Todo]:
|
||||||
|
"""
|
||||||
|
Get all todos with pagination
|
||||||
|
"""
|
||||||
|
return db.query(Todo).offset(skip).limit(limit).all()
|
||||||
|
|
||||||
|
|
||||||
|
def get_todo(db: Session, todo_id: int) -> Todo | None:
|
||||||
|
"""
|
||||||
|
Get a single todo by ID
|
||||||
|
"""
|
||||||
|
return db.query(Todo).filter(Todo.id == todo_id).first()
|
||||||
|
|
||||||
|
|
||||||
|
def create_todo(db: Session, todo: TodoCreate) -> Todo:
|
||||||
|
"""
|
||||||
|
Create a new todo
|
||||||
|
"""
|
||||||
|
db_todo = Todo(**todo.model_dump())
|
||||||
|
db.add(db_todo)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(db_todo)
|
||||||
|
return db_todo
|
||||||
|
|
||||||
|
|
||||||
|
def update_todo(
|
||||||
|
db: Session, todo_id: int, todo_update: TodoUpdate
|
||||||
|
) -> Todo | None:
|
||||||
|
"""
|
||||||
|
Update an existing todo
|
||||||
|
"""
|
||||||
|
db_todo = get_todo(db, todo_id)
|
||||||
|
if db_todo is None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
update_data = todo_update.model_dump(exclude_unset=True)
|
||||||
|
for key, value in update_data.items():
|
||||||
|
setattr(db_todo, key, value)
|
||||||
|
|
||||||
|
db.add(db_todo)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(db_todo)
|
||||||
|
return db_todo
|
||||||
|
|
||||||
|
|
||||||
|
def delete_todo(db: Session, todo_id: int) -> bool:
|
||||||
|
"""
|
||||||
|
Delete a todo by ID
|
||||||
|
"""
|
||||||
|
db_todo = get_todo(db, todo_id)
|
||||||
|
if db_todo is None:
|
||||||
|
return False
|
||||||
|
|
||||||
|
db.delete(db_todo)
|
||||||
|
db.commit()
|
||||||
|
return True
|
39
main.py
Normal file
39
main.py
Normal file
@ -0,0 +1,39 @@
|
|||||||
|
"""
|
||||||
|
FastAPI Todo Application Entry Point
|
||||||
|
"""
|
||||||
|
from fastapi import FastAPI
|
||||||
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
|
|
||||||
|
from app.api.routers import health, todos
|
||||||
|
from app.core.database import create_db_and_tables
|
||||||
|
|
||||||
|
app = FastAPI(
|
||||||
|
title="Todo API",
|
||||||
|
description="A simple Todo API built with FastAPI and SQLite",
|
||||||
|
version="0.1.0",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Configure CORS
|
||||||
|
app.add_middleware(
|
||||||
|
CORSMiddleware,
|
||||||
|
allow_origins=["*"], # Allows all origins
|
||||||
|
allow_credentials=True,
|
||||||
|
allow_methods=["*"], # Allows all methods
|
||||||
|
allow_headers=["*"], # Allows all headers
|
||||||
|
)
|
||||||
|
|
||||||
|
# Include routers
|
||||||
|
app.include_router(todos.router, prefix="/api", tags=["todos"])
|
||||||
|
app.include_router(health.router, tags=["health"])
|
||||||
|
|
||||||
|
|
||||||
|
@app.on_event("startup")
|
||||||
|
def on_startup():
|
||||||
|
"""Create database tables on application startup"""
|
||||||
|
create_db_and_tables()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
import uvicorn
|
||||||
|
|
||||||
|
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)
|
30
pyproject.toml
Normal file
30
pyproject.toml
Normal file
@ -0,0 +1,30 @@
|
|||||||
|
[tool.ruff]
|
||||||
|
line-length = 110
|
||||||
|
target-version = "py310"
|
||||||
|
|
||||||
|
[tool.ruff.lint]
|
||||||
|
# Enable Pyflakes, pycodestyle, isort, and more
|
||||||
|
select = ["E", "F", "I", "W", "N", "UP"]
|
||||||
|
|
||||||
|
ignore = []
|
||||||
|
|
||||||
|
# Allow autofix for all enabled rules (when `--fix`) is provided.
|
||||||
|
fixable = ["ALL"]
|
||||||
|
unfixable = []
|
||||||
|
|
||||||
|
# Exclude a variety of commonly ignored directories.
|
||||||
|
exclude = [
|
||||||
|
".git",
|
||||||
|
".ruff_cache",
|
||||||
|
".venv",
|
||||||
|
"__pypackages__",
|
||||||
|
"dist",
|
||||||
|
"node_modules",
|
||||||
|
"venv",
|
||||||
|
]
|
||||||
|
|
||||||
|
[tool.ruff.lint.isort]
|
||||||
|
known-third-party = ["fastapi", "pydantic", "sqlalchemy", "alembic", "uvicorn"]
|
||||||
|
|
||||||
|
[tool.ruff.lint.mccabe]
|
||||||
|
max-complexity = 10
|
8
requirements.txt
Normal file
8
requirements.txt
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
fastapi>=0.95.1
|
||||||
|
uvicorn>=0.22.0
|
||||||
|
pydantic>=2.0.0
|
||||||
|
sqlalchemy>=2.0.0
|
||||||
|
alembic>=1.11.0
|
||||||
|
python-dotenv>=1.0.0
|
||||||
|
ruff>=0.0.284
|
||||||
|
pathlib>=1.0.1
|
Loading…
x
Reference in New Issue
Block a user