Build simple todo app with FastAPI and SQLite
- Created FastAPI application with CRUD operations for todos - Implemented SQLite database with SQLAlchemy ORM - Added Alembic for database migrations - Set up CORS middleware for all origins - Added health check endpoint at /health - Created comprehensive API documentation - Formatted code with Ruff linter - Updated README with project information Features: - Create, read, update, delete todos - Pagination support for listing todos - Auto-generated OpenAPI documentation at /docs - Health monitoring endpoint
This commit is contained in:
parent
11dbb821c3
commit
cdd4aec842
69
README.md
69
README.md
@ -1,3 +1,68 @@
|
|||||||
# FastAPI Application
|
# Todo App API
|
||||||
|
|
||||||
This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform.
|
A simple Todo application API built with FastAPI and SQLite.
|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
- Create, read, update, and delete todos
|
||||||
|
- SQLite database with SQLAlchemy ORM
|
||||||
|
- Database migrations with Alembic
|
||||||
|
- CORS enabled for all origins
|
||||||
|
- Health check endpoint
|
||||||
|
- Auto-generated API documentation
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
1. Install dependencies:
|
||||||
|
```bash
|
||||||
|
pip install -r requirements.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
2. Run the application:
|
||||||
|
```bash
|
||||||
|
uvicorn main:app --reload
|
||||||
|
```
|
||||||
|
|
||||||
|
The API will be available at http://localhost:8000
|
||||||
|
|
||||||
|
## API Endpoints
|
||||||
|
|
||||||
|
- `GET /` - Root endpoint with API information
|
||||||
|
- `GET /health` - Health check endpoint
|
||||||
|
- `GET /docs` - Interactive API documentation (Swagger UI)
|
||||||
|
- `GET /redoc` - Alternative API documentation
|
||||||
|
- `POST /todos` - Create a new todo
|
||||||
|
- `GET /todos` - Get all todos (with pagination)
|
||||||
|
- `GET /todos/{todo_id}` - Get a specific todo
|
||||||
|
- `PUT /todos/{todo_id}` - Update a todo
|
||||||
|
- `DELETE /todos/{todo_id}` - Delete a todo
|
||||||
|
|
||||||
|
## Database
|
||||||
|
|
||||||
|
The application uses SQLite database stored at `/app/storage/db/db.sqlite`. Database migrations are managed with Alembic.
|
||||||
|
|
||||||
|
## Project Structure
|
||||||
|
|
||||||
|
```
|
||||||
|
├── main.py # FastAPI application entry point
|
||||||
|
├── requirements.txt # Python dependencies
|
||||||
|
├── alembic.ini # Alembic configuration
|
||||||
|
├── alembic/ # Database migrations
|
||||||
|
│ ├── env.py
|
||||||
|
│ ├── script.py.mako
|
||||||
|
│ └── versions/
|
||||||
|
│ └── 001_create_todos_table.py
|
||||||
|
└── app/
|
||||||
|
├── __init__.py
|
||||||
|
├── schemas.py # Pydantic schemas
|
||||||
|
├── db/
|
||||||
|
│ ├── __init__.py
|
||||||
|
│ ├── base.py # SQLAlchemy base
|
||||||
|
│ └── session.py # Database session
|
||||||
|
├── models/
|
||||||
|
│ ├── __init__.py
|
||||||
|
│ └── todo.py # Todo model
|
||||||
|
└── routers/
|
||||||
|
├── __init__.py
|
||||||
|
└── todos.py # Todo API endpoints
|
||||||
|
```
|
||||||
|
41
alembic.ini
Normal file
41
alembic.ini
Normal file
@ -0,0 +1,41 @@
|
|||||||
|
[alembic]
|
||||||
|
script_location = alembic
|
||||||
|
prepend_sys_path = .
|
||||||
|
version_path_separator = os
|
||||||
|
sqlalchemy.url = sqlite:////app/storage/db/db.sqlite
|
||||||
|
|
||||||
|
[post_write_hooks]
|
||||||
|
|
||||||
|
[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
|
50
alembic/env.py
Normal file
50
alembic/env.py
Normal file
@ -0,0 +1,50 @@
|
|||||||
|
from logging.config import fileConfig
|
||||||
|
from sqlalchemy import engine_from_config
|
||||||
|
from sqlalchemy import pool
|
||||||
|
from alembic import context
|
||||||
|
import sys
|
||||||
|
import os
|
||||||
|
|
||||||
|
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
|
||||||
|
|
||||||
|
from app.db.base import Base
|
||||||
|
|
||||||
|
config = context.config
|
||||||
|
|
||||||
|
if config.config_file_name is not None:
|
||||||
|
fileConfig(config.config_file_name)
|
||||||
|
|
||||||
|
target_metadata = Base.metadata
|
||||||
|
|
||||||
|
|
||||||
|
def run_migrations_offline() -> None:
|
||||||
|
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() -> None:
|
||||||
|
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
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() -> None:
|
||||||
|
${upgrades if upgrades else "pass"}
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
${downgrades if downgrades else "pass"}
|
45
alembic/versions/001_create_todos_table.py
Normal file
45
alembic/versions/001_create_todos_table.py
Normal file
@ -0,0 +1,45 @@
|
|||||||
|
"""create todos table
|
||||||
|
|
||||||
|
Revision ID: 001
|
||||||
|
Revises:
|
||||||
|
Create Date: 2024-01-01 12:00:00.000000
|
||||||
|
|
||||||
|
"""
|
||||||
|
|
||||||
|
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() -> None:
|
||||||
|
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(), nullable=True),
|
||||||
|
sa.Column(
|
||||||
|
"created_at",
|
||||||
|
sa.DateTime(),
|
||||||
|
server_default=sa.text("(CURRENT_TIMESTAMP)"),
|
||||||
|
nullable=True,
|
||||||
|
),
|
||||||
|
sa.Column(
|
||||||
|
"updated_at",
|
||||||
|
sa.DateTime(),
|
||||||
|
server_default=sa.text("(CURRENT_TIMESTAMP)"),
|
||||||
|
nullable=True,
|
||||||
|
),
|
||||||
|
sa.PrimaryKeyConstraint("id"),
|
||||||
|
)
|
||||||
|
op.create_index(op.f("ix_todos_id"), "todos", ["id"], unique=False)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
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/db/__init__.py
Normal file
0
app/db/__init__.py
Normal file
3
app/db/base.py
Normal file
3
app/db/base.py
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
from sqlalchemy.ext.declarative import declarative_base
|
||||||
|
|
||||||
|
Base = declarative_base()
|
22
app/db/session.py
Normal file
22
app/db/session.py
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
from pathlib import Path
|
||||||
|
from sqlalchemy import create_engine
|
||||||
|
from sqlalchemy.orm import sessionmaker
|
||||||
|
|
||||||
|
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)
|
||||||
|
|
||||||
|
|
||||||
|
def get_db():
|
||||||
|
db = SessionLocal()
|
||||||
|
try:
|
||||||
|
yield db
|
||||||
|
finally:
|
||||||
|
db.close()
|
0
app/models/__init__.py
Normal file
0
app/models/__init__.py
Normal file
14
app/models/todo.py
Normal file
14
app/models/todo.py
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
from sqlalchemy import Column, Integer, String, Boolean, DateTime
|
||||||
|
from sqlalchemy.sql import func
|
||||||
|
from app.db.base import Base
|
||||||
|
|
||||||
|
|
||||||
|
class Todo(Base):
|
||||||
|
__tablename__ = "todos"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
title = Column(String, nullable=False)
|
||||||
|
description = Column(String, nullable=True)
|
||||||
|
completed = Column(Boolean, default=False)
|
||||||
|
created_at = Column(DateTime, server_default=func.now())
|
||||||
|
updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now())
|
0
app/routers/__init__.py
Normal file
0
app/routers/__init__.py
Normal file
57
app/routers/todos.py
Normal file
57
app/routers/todos.py
Normal file
@ -0,0 +1,57 @@
|
|||||||
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
from typing import List
|
||||||
|
from app.db.session import get_db
|
||||||
|
from app.models.todo import Todo
|
||||||
|
from app.schemas import TodoCreate, TodoUpdate, TodoResponse
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/todos", tags=["todos"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/", response_model=TodoResponse)
|
||||||
|
def create_todo(todo: TodoCreate, db: Session = Depends(get_db)):
|
||||||
|
db_todo = Todo(**todo.dict())
|
||||||
|
db.add(db_todo)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(db_todo)
|
||||||
|
return db_todo
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/", response_model=List[TodoResponse])
|
||||||
|
def get_todos(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
|
||||||
|
todos = db.query(Todo).offset(skip).limit(limit).all()
|
||||||
|
return todos
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{todo_id}", response_model=TodoResponse)
|
||||||
|
def get_todo(todo_id: int, db: Session = Depends(get_db)):
|
||||||
|
todo = db.query(Todo).filter(Todo.id == todo_id).first()
|
||||||
|
if todo is None:
|
||||||
|
raise HTTPException(status_code=404, detail="Todo not found")
|
||||||
|
return todo
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/{todo_id}", response_model=TodoResponse)
|
||||||
|
def update_todo(todo_id: int, todo_update: TodoUpdate, db: Session = Depends(get_db)):
|
||||||
|
todo = db.query(Todo).filter(Todo.id == todo_id).first()
|
||||||
|
if todo is None:
|
||||||
|
raise HTTPException(status_code=404, detail="Todo not found")
|
||||||
|
|
||||||
|
update_data = todo_update.dict(exclude_unset=True)
|
||||||
|
for field, value in update_data.items():
|
||||||
|
setattr(todo, field, value)
|
||||||
|
|
||||||
|
db.commit()
|
||||||
|
db.refresh(todo)
|
||||||
|
return todo
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/{todo_id}")
|
||||||
|
def delete_todo(todo_id: int, db: Session = Depends(get_db)):
|
||||||
|
todo = db.query(Todo).filter(Todo.id == todo_id).first()
|
||||||
|
if todo is None:
|
||||||
|
raise HTTPException(status_code=404, detail="Todo not found")
|
||||||
|
|
||||||
|
db.delete(todo)
|
||||||
|
db.commit()
|
||||||
|
return {"message": "Todo deleted successfully"}
|
28
app/schemas.py
Normal file
28
app/schemas.py
Normal file
@ -0,0 +1,28 @@
|
|||||||
|
from pydantic import BaseModel
|
||||||
|
from typing import Optional
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
|
||||||
|
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: datetime
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
from_attributes = True
|
39
main.py
Normal file
39
main.py
Normal file
@ -0,0 +1,39 @@
|
|||||||
|
from fastapi import FastAPI
|
||||||
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
|
from app.routers import todos
|
||||||
|
from app.db.session import engine
|
||||||
|
from app.db.base import Base
|
||||||
|
|
||||||
|
Base.metadata.create_all(bind=engine)
|
||||||
|
|
||||||
|
app = FastAPI(
|
||||||
|
title="Todo App API",
|
||||||
|
description="A simple Todo application API built with FastAPI",
|
||||||
|
version="1.0.0",
|
||||||
|
openapi_url="/openapi.json",
|
||||||
|
)
|
||||||
|
|
||||||
|
app.add_middleware(
|
||||||
|
CORSMiddleware,
|
||||||
|
allow_origins=["*"],
|
||||||
|
allow_credentials=True,
|
||||||
|
allow_methods=["*"],
|
||||||
|
allow_headers=["*"],
|
||||||
|
)
|
||||||
|
|
||||||
|
app.include_router(todos.router)
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/")
|
||||||
|
def read_root():
|
||||||
|
return {
|
||||||
|
"title": "Todo App API",
|
||||||
|
"description": "A simple Todo application API built with FastAPI",
|
||||||
|
"documentation": "/docs",
|
||||||
|
"health_check": "/health",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/health")
|
||||||
|
def health_check():
|
||||||
|
return {"status": "healthy", "service": "todo-api"}
|
7
requirements.txt
Normal file
7
requirements.txt
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
fastapi==0.104.1
|
||||||
|
uvicorn==0.24.0
|
||||||
|
sqlalchemy==2.0.23
|
||||||
|
alembic==1.12.1
|
||||||
|
python-multipart==0.0.6
|
||||||
|
pydantic==2.5.0
|
||||||
|
ruff==0.1.6
|
Loading…
x
Reference in New Issue
Block a user