Create simple todo application with FastAPI and SQLite

- Set up project structure with FastAPI and SQLite
- Created Todo model with SQLAlchemy ORM
- Added CRUD operations for todos
- Implemented API endpoints for Todo operations
- Added health check endpoint
- Added Alembic for database migrations
- Updated README with documentation

generated with BackendIM... (backend.im)
This commit is contained in:
Automated Action 2025-05-13 12:04:52 +00:00
parent ecdfe867cd
commit 43ed4aaa3f
18 changed files with 506 additions and 2 deletions

View File

@ -1,3 +1,95 @@
# FastAPI Application # Simple Todo Application
This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform. A simple RESTful Todo application API built with FastAPI and SQLite.
## Features
- Create, read, update, and delete todo items
- SQLite database with SQLAlchemy ORM
- Alembic for database migrations
- Health check endpoint
- API documentation with Swagger UI
## Installation
1. Clone the repository:
```bash
git clone [repository-url]
cd simpletodoapplication
```
2. Install dependencies:
```bash
pip install -r requirements.txt
```
3. Apply database migrations:
```bash
alembic upgrade head
```
## Running the Application
Start the application with Uvicorn:
```bash
uvicorn main:app --reload
```
The API will be available at `http://localhost:8000`.
API documentation is available at:
- Swagger UI: `http://localhost:8000/docs`
- ReDoc: `http://localhost:8000/redoc`
## API Endpoints
### Todos
- `GET /api/todos/` - List all todos
- `POST /api/todos/` - Create a new todo
- `GET /api/todos/{todo_id}` - Get a specific todo
- `PUT /api/todos/{todo_id}` - Update a todo
- `DELETE /api/todos/{todo_id}` - Delete a todo
### Health Check
- `GET /health` - Health check endpoint
## Project Structure
```
.
├── alembic/ # Database migration scripts
├── app/
│ ├── api/ # API routes
│ │ ├── health.py # Health check endpoint
│ │ └── todos.py # Todo API endpoints
│ ├── database/ # Database related code
│ │ ├── base.py # Database connection setup
│ │ └── crud.py # CRUD operations
│ ├── models/ # Data models
│ │ ├── schemas.py # Pydantic schemas
│ │ └── todo.py # SQLAlchemy Todo model
│ └── storage/
│ └── db/ # SQLite database files
├── main.py # FastAPI application entry point
├── requirements.txt # Project dependencies
└── README.md # Project documentation
```
## Database Schema
### Todo
| Column | Type | Description |
|-------------|-----------|-------------------------------|
| id | Integer | Primary key |
| title | String | Todo title |
| description | String | Todo description (optional) |
| completed | Boolean | Todo completion status |
| created_at | DateTime | Creation timestamp |
| updated_at | DateTime | Last update timestamp |

40
alembic.ini Normal file
View File

@ -0,0 +1,40 @@
[alembic]
script_location = alembic
prepend_sys_path = .
# SQLite URL example
sqlalchemy.url = sqlite:///app/storage/db/db.sqlite
[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

9
alembic/README Normal file
View File

@ -0,0 +1,9 @@
Generic single-database configuration for the Todo application.
This directory contains Alembic migration scripts for database schema changes.
To apply migrations:
alembic upgrade head
To create a new migration:
alembic revision -m "description"

79
alembic/env.py Normal file
View File

@ -0,0 +1,79 @@
from logging.config import fileConfig
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from alembic import context
# Import Base from app
from app.database.base import Base
from app.models.todo import Todo
# 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
# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.
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:
context.configure(
connection=connection, target_metadata=target_metadata
)
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
View 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"}

View File

@ -0,0 +1,36 @@
"""create todos table
Revision ID: 001
Revises:
Create Date: 2023-05-13
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '001'
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(), nullable=False),
sa.Column('description', sa.String(), nullable=True),
sa.Column('completed', sa.Boolean(), default=False),
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('(CURRENT_TIMESTAMP)')),
sa.Column('updated_at', sa.DateTime(timezone=True), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_todos_id'), 'todos', ['id'], unique=False)
op.create_index(op.f('ix_todos_title'), 'todos', ['title'], unique=False)
def downgrade():
op.drop_index(op.f('ix_todos_title'), table_name='todos')
op.drop_index(op.f('ix_todos_id'), table_name='todos')
op.drop_table('todos')

1
app/__init__.py Normal file
View File

@ -0,0 +1 @@
# This file is intentionally left empty to make the directory a Python package

1
app/api/__init__.py Normal file
View File

@ -0,0 +1 @@
# This file is intentionally left empty to make the directory a Python package

25
app/api/health.py Normal file
View File

@ -0,0 +1,25 @@
from fastapi import APIRouter, Depends, status
from sqlalchemy.orm import Session
from sqlalchemy import text
from app.database.base import get_db
router = APIRouter()
@router.get("/health", status_code=status.HTTP_200_OK)
def health_check(db: Session = Depends(get_db)):
"""
Health check endpoint to verify the API and database are operational.
"""
# Check database connection
try:
db.execute(text("SELECT 1"))
db_status = "healthy"
except Exception as e:
db_status = f"unhealthy: {str(e)}"
return {
"status": "healthy",
"database": db_status,
"version": "0.1.0"
}

58
app/api/todos.py Normal file
View File

@ -0,0 +1,58 @@
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List, Optional
from app.database.base import get_db
from app.database import crud
from app.models.schemas import TodoCreate, TodoResponse, TodoUpdate
router = APIRouter()
@router.get("/todos/", response_model=List[TodoResponse])
def read_todos(
skip: int = 0,
limit: int = 100,
db: Session = Depends(get_db)
):
"""
Retrieve all todos with pagination support.
"""
todos = crud.get_todos(db, skip=skip, limit=limit)
return todos
@router.get("/todos/{todo_id}", response_model=TodoResponse)
def read_todo(todo_id: int, db: Session = Depends(get_db)):
"""
Retrieve a specific todo by its ID.
"""
db_todo = crud.get_todo(db, todo_id=todo_id)
if db_todo is None:
raise HTTPException(status_code=404, detail="Todo not found")
return db_todo
@router.post("/todos/", response_model=TodoResponse, status_code=status.HTTP_201_CREATED)
def create_todo(todo: TodoCreate, db: Session = Depends(get_db)):
"""
Create a new todo.
"""
return crud.create_todo(db=db, todo=todo)
@router.put("/todos/{todo_id}", response_model=TodoResponse)
def update_todo(todo_id: int, todo: TodoUpdate, db: Session = Depends(get_db)):
"""
Update a todo by its ID.
"""
db_todo = crud.update_todo(db, todo_id=todo_id, todo=todo)
if db_todo is None:
raise HTTPException(status_code=404, detail="Todo not found")
return db_todo
@router.delete("/todos/{todo_id}", response_model=TodoResponse)
def delete_todo(todo_id: int, db: Session = Depends(get_db)):
"""
Delete a todo by its ID.
"""
db_todo = crud.delete_todo(db, todo_id=todo_id)
if db_todo is None:
raise HTTPException(status_code=404, detail="Todo not found")
return db_todo

1
app/database/__init__.py Normal file
View File

@ -0,0 +1 @@
# This file is intentionally left empty to make the directory a Python package

27
app/database/base.py Normal file
View File

@ -0,0 +1,27 @@
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()
# Dependency
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()

34
app/database/crud.py Normal file
View File

@ -0,0 +1,34 @@
from sqlalchemy.orm import Session
from app.models.todo import Todo
from app.models.schemas import TodoCreate, TodoUpdate
# Todo CRUD operations
def get_todos(db: Session, skip: int = 0, limit: int = 100):
return db.query(Todo).offset(skip).limit(limit).all()
def get_todo(db: Session, todo_id: int):
return db.query(Todo).filter(Todo.id == todo_id).first()
def create_todo(db: Session, todo: TodoCreate):
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: TodoUpdate):
db_todo = get_todo(db, todo_id)
if db_todo:
update_data = todo.model_dump(exclude_unset=True)
for key, value in update_data.items():
setattr(db_todo, key, value)
db.commit()
db.refresh(db_todo)
return db_todo
def delete_todo(db: Session, todo_id: int):
db_todo = get_todo(db, todo_id)
if db_todo:
db.delete(db_todo)
db.commit()
return db_todo

2
app/models/__init__.py Normal file
View File

@ -0,0 +1,2 @@
# Import models for easy access
from app.models.todo import Todo

25
app/models/schemas.py Normal file
View File

@ -0,0 +1,25 @@
from datetime import datetime
from typing import Optional
from pydantic import BaseModel
# Todo schemas
class TodoBase(BaseModel):
title: str
description: Optional[str] = None
completed: bool = False
class TodoCreate(TodoBase):
pass
class TodoUpdate(BaseModel):
title: Optional[str] = None
description: Optional[str] = None
completed: Optional[bool] = None
class TodoResponse(TodoBase):
id: int
created_at: datetime
updated_at: Optional[datetime] = None
class Config:
from_attributes = True

13
app/models/todo.py Normal file
View File

@ -0,0 +1,13 @@
from sqlalchemy import Column, Integer, String, Boolean, DateTime
from sqlalchemy.sql import func
from app.database.base import Base
class Todo(Base):
__tablename__ = "todos"
id = Column(Integer, primary_key=True, index=True)
title = Column(String, index=True)
description = Column(String)
completed = Column(Boolean, default=False)
created_at = Column(DateTime(timezone=True), server_default=func.now())
updated_at = Column(DateTime(timezone=True), onupdate=func.now())

31
main.py Normal file
View File

@ -0,0 +1,31 @@
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.api import todos, health
from app.database.base import engine, Base
# Create tables
Base.metadata.create_all(bind=engine)
app = FastAPI(
title="Todo Application API",
description="A simple Todo application API built with FastAPI and SQLite",
version="0.1.0",
)
# Add CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Include routers
app.include_router(todos.router, prefix="/api", tags=["todos"])
app.include_router(health.router, tags=["health"])
if __name__ == "__main__":
import uvicorn
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)

6
requirements.txt Normal file
View File

@ -0,0 +1,6 @@
fastapi==0.109.2
uvicorn==0.27.1
sqlalchemy==2.0.25
pydantic==2.5.3
alembic==1.12.1
python-dotenv==1.0.0