Setup basic FastAPI project with Todo API
- Created requirements.txt with necessary dependencies - Set up FastAPI application structure with main.py - Added health endpoint - Configured SQLAlchemy with SQLite database - Initialized Alembic for database migrations - Created Todo model and API endpoints - Updated README with setup and usage instructions - Linted code with Ruff
This commit is contained in:
parent
31cda897a0
commit
9c5b74200b
144
README.md
144
README.md
@ -1,3 +1,143 @@
|
||||
# FastAPI Application
|
||||
# Todo List API
|
||||
|
||||
This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform.
|
||||
A simple Todo List API built with FastAPI and SQLite. This API allows you to create, read, update, and delete todo items.
|
||||
|
||||
## Features
|
||||
|
||||
- RESTful API with CRUD operations for todo items
|
||||
- SQLite database with SQLAlchemy ORM
|
||||
- Database migrations with Alembic
|
||||
- Auto-generated API documentation with Swagger UI and ReDoc
|
||||
- Health check endpoint
|
||||
- Code linting with Ruff
|
||||
|
||||
## Requirements
|
||||
|
||||
- Python 3.8+
|
||||
- FastAPI
|
||||
- SQLAlchemy
|
||||
- Alembic
|
||||
- Uvicorn
|
||||
- SQLite
|
||||
|
||||
## Setup
|
||||
|
||||
1. Clone the repository
|
||||
2. Install the dependencies:
|
||||
```bash
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
3. Run the database migrations:
|
||||
```bash
|
||||
alembic upgrade head
|
||||
```
|
||||
4. Start the API server:
|
||||
```bash
|
||||
uvicorn main:app --host 0.0.0.0 --port 8000 --reload
|
||||
```
|
||||
|
||||
## API Endpoints
|
||||
|
||||
- `GET /`: Root endpoint with welcome message
|
||||
- `GET /health`: Health check endpoint
|
||||
- `GET /docs`: Auto-generated API documentation (Swagger UI)
|
||||
- `GET /redoc`: Alternative API documentation (ReDoc)
|
||||
- `GET /openapi.json`: OpenAPI schema
|
||||
|
||||
### Todo Endpoints
|
||||
|
||||
- `GET /todos`: Get all todo items
|
||||
- `GET /todos/{todo_id}`: Get a specific todo item
|
||||
- `POST /todos`: Create a new todo item
|
||||
- `PUT /todos/{todo_id}`: Update a todo item
|
||||
- `DELETE /todos/{todo_id}`: Delete a todo item
|
||||
|
||||
## API Usage Examples
|
||||
|
||||
### Create a Todo Item
|
||||
|
||||
```bash
|
||||
curl -X 'POST' \
|
||||
'http://localhost:8000/todos' \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{
|
||||
"title": "Buy groceries",
|
||||
"description": "Milk, eggs, bread",
|
||||
"completed": false
|
||||
}'
|
||||
```
|
||||
|
||||
### Get All Todo Items
|
||||
|
||||
```bash
|
||||
curl -X 'GET' 'http://localhost:8000/todos'
|
||||
```
|
||||
|
||||
### Get a Specific Todo Item
|
||||
|
||||
```bash
|
||||
curl -X 'GET' 'http://localhost:8000/todos/1'
|
||||
```
|
||||
|
||||
### Update a Todo Item
|
||||
|
||||
```bash
|
||||
curl -X 'PUT' \
|
||||
'http://localhost:8000/todos/1' \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{
|
||||
"title": "Buy groceries",
|
||||
"description": "Milk, eggs, bread, cheese",
|
||||
"completed": true
|
||||
}'
|
||||
```
|
||||
|
||||
### Delete a Todo Item
|
||||
|
||||
```bash
|
||||
curl -X 'DELETE' 'http://localhost:8000/todos/1'
|
||||
```
|
||||
|
||||
## Database Schema
|
||||
|
||||
The database schema consists of a single `todos` table with the following columns:
|
||||
|
||||
- `id`: Integer, Primary Key
|
||||
- `title`: String, Not Null
|
||||
- `description`: String, Nullable
|
||||
- `completed`: Boolean, Default: False
|
||||
- `created_at`: DateTime, Default: Current Timestamp
|
||||
- `updated_at`: DateTime, Nullable
|
||||
|
||||
## Development
|
||||
|
||||
For local development, you can use the following commands:
|
||||
|
||||
- Start the application with auto-reload:
|
||||
```bash
|
||||
uvicorn main:app --reload
|
||||
```
|
||||
|
||||
- Run Ruff for linting:
|
||||
```bash
|
||||
ruff check .
|
||||
```
|
||||
|
||||
- Run Ruff for auto-fix:
|
||||
```bash
|
||||
ruff check --fix .
|
||||
```
|
||||
|
||||
- Create a new migration:
|
||||
```bash
|
||||
alembic revision -m "Your migration message"
|
||||
```
|
||||
|
||||
- Run migrations:
|
||||
```bash
|
||||
alembic upgrade head
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
This project is licensed under the MIT License.
|
104
alembic.ini
Normal file
104
alembic.ini
Normal file
@ -0,0 +1,104 @@
|
||||
# A generic, single database configuration.
|
||||
|
||||
[alembic]
|
||||
# path to migration scripts
|
||||
script_location = migrations
|
||||
|
||||
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
|
||||
# Uncomment the line below if you want the files to be prepended with date and time
|
||||
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
|
||||
# for all available tokens
|
||||
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
|
||||
|
||||
# sys.path path, will be prepended to sys.path if present.
|
||||
# defaults to the current working directory.
|
||||
prepend_sys_path = .
|
||||
|
||||
# timezone to use when rendering the date within the migration file
|
||||
# as well as the filename.
|
||||
# If specified, requires the python-dateutil library that can be
|
||||
# installed by adding `python-dateutil` to the [tool.poetry.dependencies]
|
||||
# section of your pyproject.toml file
|
||||
# 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.
|
||||
# The path separator used here should be the separator specified by "version_path_separator" below.
|
||||
# version_locations = %(here)s/bar:%(here)s/bat:migrations/versions
|
||||
|
||||
# version path separator; As mentioned above, this is the character used to split
|
||||
# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep.
|
||||
# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas.
|
||||
# Valid values for version_path_separator are:
|
||||
#
|
||||
# version_path_separator = :
|
||||
# version_path_separator = ;
|
||||
# version_path_separator = space
|
||||
version_path_separator = os # Use os.pathsep. Default configuration used to be "space".
|
||||
|
||||
# the output encoding used when revision files
|
||||
# are written from script.py.mako
|
||||
# output_encoding = utf-8
|
||||
|
||||
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 REVISION_SCRIPT_FILENAME
|
||||
|
||||
# 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
|
1
app/__init__.py
Normal file
1
app/__init__.py
Normal file
@ -0,0 +1 @@
|
||||
# App package initialization
|
1
app/database/__init__.py
Normal file
1
app/database/__init__.py
Normal file
@ -0,0 +1 @@
|
||||
# Database package initialization
|
31
app/database/config.py
Normal file
31
app/database/config.py
Normal file
@ -0,0 +1,31 @@
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from pathlib import Path
|
||||
|
||||
# Create the database directory if it doesn't exist
|
||||
DB_DIR = Path("/app/storage/db")
|
||||
DB_DIR.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# SQLite database URL
|
||||
SQLALCHEMY_DATABASE_URL = f"sqlite:///{DB_DIR}/db.sqlite"
|
||||
|
||||
# Create the SQLAlchemy engine
|
||||
engine = create_engine(
|
||||
SQLALCHEMY_DATABASE_URL,
|
||||
connect_args={"check_same_thread": False}
|
||||
)
|
||||
|
||||
# Create a SessionLocal class
|
||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
|
||||
# Create a Base class for declarative models
|
||||
Base = declarative_base()
|
||||
|
||||
# Dependency to get a database session
|
||||
def get_db():
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
13
app/database/models.py
Normal file
13
app/database/models.py
Normal file
@ -0,0 +1,13 @@
|
||||
from sqlalchemy import Boolean, Column, Integer, String, DateTime
|
||||
from sqlalchemy.sql import func
|
||||
from .config import Base
|
||||
|
||||
class Todo(Base):
|
||||
__tablename__ = "todos"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
title = Column(String, index=True)
|
||||
description = Column(String, nullable=True)
|
||||
completed = Column(Boolean, default=False)
|
||||
created_at = Column(DateTime(timezone=True), server_default=func.now())
|
||||
updated_at = Column(DateTime(timezone=True), onupdate=func.now())
|
128
main.py
Normal file
128
main.py
Normal file
@ -0,0 +1,128 @@
|
||||
from fastapi import FastAPI, Depends, HTTPException, status
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from sqlalchemy.orm import Session
|
||||
import uvicorn
|
||||
from typing import List, Optional
|
||||
from pydantic import BaseModel
|
||||
from datetime import datetime
|
||||
|
||||
# Import database models and config
|
||||
from app.database.config import get_db
|
||||
from app.database.models import Todo as TodoModel
|
||||
|
||||
# Create tables if they don't exist
|
||||
# In production, you should use Alembic migrations instead
|
||||
# models.Base.metadata.create_all(bind=engine)
|
||||
|
||||
# Pydantic models for request and response
|
||||
class TodoBase(BaseModel):
|
||||
title: str
|
||||
description: Optional[str] = None
|
||||
completed: bool = False
|
||||
|
||||
class TodoCreate(TodoBase):
|
||||
pass
|
||||
|
||||
class TodoResponse(TodoBase):
|
||||
id: int
|
||||
created_at: datetime
|
||||
updated_at: Optional[datetime] = None
|
||||
|
||||
class Config:
|
||||
orm_mode = True
|
||||
|
||||
# Create the FastAPI app
|
||||
app = FastAPI(
|
||||
title="Todo List API",
|
||||
description="A simple Todo List API built with FastAPI",
|
||||
version="0.1.0",
|
||||
)
|
||||
|
||||
# Configure CORS
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
# Health endpoint
|
||||
@app.get("/health", tags=["Health"])
|
||||
async def health_check():
|
||||
"""
|
||||
Health check endpoint to verify the API is running.
|
||||
"""
|
||||
return {"status": "healthy"}
|
||||
|
||||
# Root endpoint
|
||||
@app.get("/", tags=["Root"])
|
||||
async def root():
|
||||
"""
|
||||
Root endpoint that redirects to the API documentation.
|
||||
"""
|
||||
return {"message": "Welcome to Todo List API. Visit /docs for documentation."}
|
||||
|
||||
# Todo API endpoints
|
||||
@app.post("/todos", response_model=TodoResponse, status_code=status.HTTP_201_CREATED, tags=["Todos"])
|
||||
def create_todo(todo: TodoCreate, db: Session = Depends(get_db)):
|
||||
"""
|
||||
Create a new todo item.
|
||||
"""
|
||||
db_todo = TodoModel(**todo.dict())
|
||||
db.add(db_todo)
|
||||
db.commit()
|
||||
db.refresh(db_todo)
|
||||
return db_todo
|
||||
|
||||
@app.get("/todos", response_model=List[TodoResponse], tags=["Todos"])
|
||||
def read_todos(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
|
||||
"""
|
||||
Get all todo items with pagination.
|
||||
"""
|
||||
todos = db.query(TodoModel).offset(skip).limit(limit).all()
|
||||
return todos
|
||||
|
||||
@app.get("/todos/{todo_id}", response_model=TodoResponse, tags=["Todos"])
|
||||
def read_todo(todo_id: int, db: Session = Depends(get_db)):
|
||||
"""
|
||||
Get a specific todo item by ID.
|
||||
"""
|
||||
db_todo = db.query(TodoModel).filter(TodoModel.id == todo_id).first()
|
||||
if db_todo is None:
|
||||
raise HTTPException(status_code=404, detail="Todo not found")
|
||||
return db_todo
|
||||
|
||||
@app.put("/todos/{todo_id}", response_model=TodoResponse, tags=["Todos"])
|
||||
def update_todo(todo_id: int, todo: TodoCreate, db: Session = Depends(get_db)):
|
||||
"""
|
||||
Update a todo item.
|
||||
"""
|
||||
db_todo = db.query(TodoModel).filter(TodoModel.id == todo_id).first()
|
||||
if db_todo is None:
|
||||
raise HTTPException(status_code=404, detail="Todo not found")
|
||||
|
||||
# Update todo item fields
|
||||
for key, value in todo.dict().items():
|
||||
setattr(db_todo, key, value)
|
||||
|
||||
db.commit()
|
||||
db.refresh(db_todo)
|
||||
return db_todo
|
||||
|
||||
@app.delete("/todos/{todo_id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None, tags=["Todos"])
|
||||
def delete_todo(todo_id: int, db: Session = Depends(get_db)):
|
||||
"""
|
||||
Delete a todo item.
|
||||
"""
|
||||
db_todo = db.query(TodoModel).filter(TodoModel.id == todo_id).first()
|
||||
if db_todo is None:
|
||||
raise HTTPException(status_code=404, detail="Todo not found")
|
||||
|
||||
db.delete(db_todo)
|
||||
db.commit()
|
||||
return None
|
||||
|
||||
# For local development
|
||||
if __name__ == "__main__":
|
||||
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)
|
1
migrations/__init__.py
Normal file
1
migrations/__init__.py
Normal file
@ -0,0 +1 @@
|
||||
# Migrations package initialization
|
88
migrations/env.py
Normal file
88
migrations/env.py
Normal file
@ -0,0 +1,88 @@
|
||||
from logging.config import fileConfig
|
||||
|
||||
from sqlalchemy import engine_from_config
|
||||
from sqlalchemy import pool
|
||||
|
||||
from alembic import context
|
||||
|
||||
# Import your models here
|
||||
from app.database.models import Base
|
||||
from app.database.config import SQLALCHEMY_DATABASE_URL
|
||||
|
||||
# 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
|
||||
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() -> None:
|
||||
"""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 = SQLALCHEMY_DATABASE_URL
|
||||
context.configure(
|
||||
url=url,
|
||||
target_metadata=target_metadata,
|
||||
literal_binds=True,
|
||||
dialect_opts={"paramstyle": "named"},
|
||||
render_as_batch=True, # Important for SQLite
|
||||
)
|
||||
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
def run_migrations_online() -> None:
|
||||
"""Run migrations in 'online' mode.
|
||||
|
||||
In this scenario we need to create an Engine
|
||||
and associate a connection with the context.
|
||||
|
||||
"""
|
||||
configuration = config.get_section(config.config_ini_section)
|
||||
configuration["sqlalchemy.url"] = SQLALCHEMY_DATABASE_URL
|
||||
connectable = engine_from_config(
|
||||
configuration,
|
||||
prefix="sqlalchemy.",
|
||||
poolclass=pool.NullPool,
|
||||
)
|
||||
|
||||
with connectable.connect() as connection:
|
||||
# Check if we're dealing with SQLite
|
||||
is_sqlite = connection.dialect.name == "sqlite"
|
||||
|
||||
context.configure(
|
||||
connection=connection,
|
||||
target_metadata=target_metadata,
|
||||
render_as_batch=is_sqlite, # Important for SQLite
|
||||
)
|
||||
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
if context.is_offline_mode():
|
||||
run_migrations_offline()
|
||||
else:
|
||||
run_migrations_online()
|
24
migrations/script.py.mako
Normal file
24
migrations/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"}
|
1
migrations/versions/__init__.py
Normal file
1
migrations/versions/__init__.py
Normal file
@ -0,0 +1 @@
|
||||
# Migrations versions package initialization
|
39
migrations/versions/initial_migration.py
Normal file
39
migrations/versions/initial_migration.py
Normal file
@ -0,0 +1,39 @@
|
||||
"""Initial migration
|
||||
|
||||
Revision ID: 001
|
||||
Revises:
|
||||
Create Date: 2023-10-24
|
||||
|
||||
"""
|
||||
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:
|
||||
# Create todos table
|
||||
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=False, 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() -> None:
|
||||
# Drop todos table
|
||||
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')
|
7
requirements.txt
Normal file
7
requirements.txt
Normal file
@ -0,0 +1,7 @@
|
||||
fastapi>=0.104.0
|
||||
uvicorn>=0.23.2
|
||||
sqlalchemy>=2.0.0
|
||||
alembic>=1.12.0
|
||||
pydantic>=2.4.0
|
||||
python-dotenv>=1.0.0
|
||||
ruff>=0.1.3
|
Loading…
x
Reference in New Issue
Block a user