Add FastAPI REST API service with CRUD operations
- Created main FastAPI application with CORS middleware - Added SQLite database configuration with SQLAlchemy - Implemented Items model with create, read, update, delete operations - Set up Alembic migrations for database schema management - Added comprehensive API endpoints at /api/v1/items/ - Included health check endpoint at /health - Added proper Pydantic schemas for request/response validation - Updated README with complete documentation and usage instructions - Configured Ruff for code linting and formatting
This commit is contained in:
parent
9ea61ac66d
commit
02cc12cad8
86
README.md
86
README.md
@ -1,3 +1,85 @@
|
|||||||
# FastAPI Application
|
# REST API Service
|
||||||
|
|
||||||
This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform.
|
A FastAPI-based REST API service with CRUD operations, SQLite database, and Alembic migrations.
|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
- FastAPI framework with automatic API documentation
|
||||||
|
- SQLite database with SQLAlchemy ORM
|
||||||
|
- Database migrations with Alembic
|
||||||
|
- CRUD operations for Items
|
||||||
|
- CORS enabled for all origins
|
||||||
|
- Health check endpoint
|
||||||
|
- Automatic OpenAPI documentation
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
1. Install dependencies:
|
||||||
|
```bash
|
||||||
|
pip install -r requirements.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
## Running the Application
|
||||||
|
|
||||||
|
Start the development server:
|
||||||
|
```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`
|
||||||
|
- OpenAPI JSON: `http://localhost:8000/openapi.json`
|
||||||
|
|
||||||
|
## API Endpoints
|
||||||
|
|
||||||
|
### Root
|
||||||
|
- `GET /` - Service information
|
||||||
|
|
||||||
|
### Health Check
|
||||||
|
- `GET /health` - Health status
|
||||||
|
|
||||||
|
### Items (CRUD)
|
||||||
|
- `POST /api/v1/items/` - Create a new item
|
||||||
|
- `GET /api/v1/items/` - List all items (with pagination)
|
||||||
|
- `GET /api/v1/items/{item_id}` - Get specific item
|
||||||
|
- `PUT /api/v1/items/{item_id}` - Update specific item
|
||||||
|
- `DELETE /api/v1/items/{item_id}` - Delete specific item
|
||||||
|
|
||||||
|
## Database
|
||||||
|
|
||||||
|
The application uses SQLite with the database file stored at `/app/storage/db/db.sqlite`.
|
||||||
|
|
||||||
|
### Migrations
|
||||||
|
|
||||||
|
Database migrations are managed with Alembic. The migration files are in the `alembic/versions/` directory.
|
||||||
|
|
||||||
|
## 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_items_table.py
|
||||||
|
└── app/
|
||||||
|
├── api/ # API routes
|
||||||
|
│ └── items.py
|
||||||
|
├── db/ # Database configuration
|
||||||
|
│ ├── base.py
|
||||||
|
│ └── session.py
|
||||||
|
├── models/ # SQLAlchemy models
|
||||||
|
│ └── item.py
|
||||||
|
└── schemas/ # Pydantic schemas
|
||||||
|
└── item.py
|
||||||
|
```
|
||||||
|
|
||||||
|
## Environment Variables
|
||||||
|
|
||||||
|
No environment variables are required for basic operation. The application uses SQLite with a file-based database.
|
||||||
|
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.dirname(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"}
|
41
alembic/versions/001_create_items_table.py
Normal file
41
alembic/versions/001_create_items_table.py
Normal file
@ -0,0 +1,41 @@
|
|||||||
|
"""create items table
|
||||||
|
|
||||||
|
Revision ID: 001
|
||||||
|
Revises:
|
||||||
|
Create Date: 2024-01-01 00: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(
|
||||||
|
"items",
|
||||||
|
sa.Column("id", sa.Integer(), nullable=False),
|
||||||
|
sa.Column("name", sa.String(length=100), nullable=False),
|
||||||
|
sa.Column("description", sa.Text(), nullable=True),
|
||||||
|
sa.Column(
|
||||||
|
"created_at",
|
||||||
|
sa.DateTime(timezone=True),
|
||||||
|
server_default=sa.text("(CURRENT_TIMESTAMP)"),
|
||||||
|
nullable=True,
|
||||||
|
),
|
||||||
|
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=True),
|
||||||
|
sa.PrimaryKeyConstraint("id"),
|
||||||
|
)
|
||||||
|
op.create_index(op.f("ix_items_id"), "items", ["id"], unique=False)
|
||||||
|
op.create_index(op.f("ix_items_name"), "items", ["name"], unique=False)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_index(op.f("ix_items_name"), table_name="items")
|
||||||
|
op.drop_index(op.f("ix_items_id"), table_name="items")
|
||||||
|
op.drop_table("items")
|
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
57
app/api/items.py
Normal file
57
app/api/items.py
Normal file
@ -0,0 +1,57 @@
|
|||||||
|
from fastapi import APIRouter, Depends, HTTPException, status
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
from typing import List
|
||||||
|
from app.db.session import get_db
|
||||||
|
from app.models.item import Item
|
||||||
|
from app.schemas.item import Item as ItemSchema, ItemCreate, ItemUpdate
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/items/", response_model=ItemSchema, status_code=status.HTTP_201_CREATED)
|
||||||
|
def create_item(item: ItemCreate, db: Session = Depends(get_db)):
|
||||||
|
db_item = Item(**item.dict())
|
||||||
|
db.add(db_item)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(db_item)
|
||||||
|
return db_item
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/items/", response_model=List[ItemSchema])
|
||||||
|
def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
|
||||||
|
items = db.query(Item).offset(skip).limit(limit).all()
|
||||||
|
return items
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/items/{item_id}", response_model=ItemSchema)
|
||||||
|
def read_item(item_id: int, db: Session = Depends(get_db)):
|
||||||
|
item = db.query(Item).filter(Item.id == item_id).first()
|
||||||
|
if item is None:
|
||||||
|
raise HTTPException(status_code=404, detail="Item not found")
|
||||||
|
return item
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/items/{item_id}", response_model=ItemSchema)
|
||||||
|
def update_item(item_id: int, item_update: ItemUpdate, db: Session = Depends(get_db)):
|
||||||
|
item = db.query(Item).filter(Item.id == item_id).first()
|
||||||
|
if item is None:
|
||||||
|
raise HTTPException(status_code=404, detail="Item not found")
|
||||||
|
|
||||||
|
update_data = item_update.dict(exclude_unset=True)
|
||||||
|
for field, value in update_data.items():
|
||||||
|
setattr(item, field, value)
|
||||||
|
|
||||||
|
db.commit()
|
||||||
|
db.refresh(item)
|
||||||
|
return item
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/items/{item_id}")
|
||||||
|
def delete_item(item_id: int, db: Session = Depends(get_db)):
|
||||||
|
item = db.query(Item).filter(Item.id == item_id).first()
|
||||||
|
if item is None:
|
||||||
|
raise HTTPException(status_code=404, detail="Item not found")
|
||||||
|
|
||||||
|
db.delete(item)
|
||||||
|
db.commit()
|
||||||
|
return {"message": "Item deleted successfully"}
|
0
app/db/__init__.py
Normal file
0
app/db/__init__.py
Normal file
17
app/db/base.py
Normal file
17
app/db/base.py
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
from sqlalchemy import create_engine
|
||||||
|
from sqlalchemy.ext.declarative import declarative_base
|
||||||
|
from sqlalchemy.orm import sessionmaker
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
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()
|
9
app/db/session.py
Normal file
9
app/db/session.py
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
from .base import SessionLocal
|
||||||
|
|
||||||
|
|
||||||
|
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
13
app/models/item.py
Normal file
13
app/models/item.py
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
from sqlalchemy import Column, Integer, String, Text, DateTime
|
||||||
|
from sqlalchemy.sql import func
|
||||||
|
from app.db.base import Base
|
||||||
|
|
||||||
|
|
||||||
|
class Item(Base):
|
||||||
|
__tablename__ = "items"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
name = Column(String(100), nullable=False, index=True)
|
||||||
|
description = Column(Text, nullable=True)
|
||||||
|
created_at = Column(DateTime(timezone=True), server_default=func.now())
|
||||||
|
updated_at = Column(DateTime(timezone=True), onupdate=func.now())
|
0
app/schemas/__init__.py
Normal file
0
app/schemas/__init__.py
Normal file
26
app/schemas/item.py
Normal file
26
app/schemas/item.py
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
from pydantic import BaseModel
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
|
||||||
|
class ItemBase(BaseModel):
|
||||||
|
name: str
|
||||||
|
description: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
class ItemCreate(ItemBase):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class ItemUpdate(BaseModel):
|
||||||
|
name: Optional[str] = None
|
||||||
|
description: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
class Item(ItemBase):
|
||||||
|
id: int
|
||||||
|
created_at: datetime
|
||||||
|
updated_at: Optional[datetime] = None
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
from_attributes = True
|
42
main.py
Normal file
42
main.py
Normal file
@ -0,0 +1,42 @@
|
|||||||
|
from fastapi import FastAPI
|
||||||
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
|
import uvicorn
|
||||||
|
from app.api.items import router as items_router
|
||||||
|
from app.db.base import engine, Base
|
||||||
|
|
||||||
|
Base.metadata.create_all(bind=engine)
|
||||||
|
|
||||||
|
app = FastAPI(
|
||||||
|
title="REST API Service",
|
||||||
|
description="A FastAPI REST API service",
|
||||||
|
version="1.0.0",
|
||||||
|
openapi_url="/openapi.json",
|
||||||
|
)
|
||||||
|
|
||||||
|
app.add_middleware(
|
||||||
|
CORSMiddleware,
|
||||||
|
allow_origins=["*"],
|
||||||
|
allow_credentials=True,
|
||||||
|
allow_methods=["*"],
|
||||||
|
allow_headers=["*"],
|
||||||
|
)
|
||||||
|
|
||||||
|
app.include_router(items_router, prefix="/api/v1", tags=["items"])
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/")
|
||||||
|
async def root():
|
||||||
|
return {
|
||||||
|
"title": "REST API Service",
|
||||||
|
"documentation": "/docs",
|
||||||
|
"health_check": "/health",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/health")
|
||||||
|
async def health_check():
|
||||||
|
return {"status": "healthy", "service": "REST API Service"}
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
uvicorn.run(app, host="0.0.0.0", port=8000)
|
7
requirements.txt
Normal file
7
requirements.txt
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
fastapi==0.104.1
|
||||||
|
uvicorn[standard]==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