Create FastAPI REST API service with SQLite database
- Set up FastAPI application with CORS support - Implement SQLite database with SQLAlchemy ORM - Create User model with CRUD operations - Add Alembic for database migrations - Include health check and documentation endpoints - Set up proper project structure with organized modules - Add comprehensive README with setup instructions - Configure Ruff for code linting and formatting
This commit is contained in:
parent
b362c4f692
commit
16d63c4168
89
README.md
89
README.md
@ -1,3 +1,88 @@
|
||||
# FastAPI Application
|
||||
# REST API Service
|
||||
|
||||
This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform.
|
||||
A REST API service built with FastAPI and SQLite, providing user management functionality.
|
||||
|
||||
## Features
|
||||
|
||||
- FastAPI web framework
|
||||
- SQLite database with SQLAlchemy ORM
|
||||
- Alembic database migrations
|
||||
- CRUD operations for users
|
||||
- Health check endpoint
|
||||
- Auto-generated OpenAPI documentation
|
||||
- CORS support
|
||||
|
||||
## 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_initial_migration.py
|
||||
└── app/
|
||||
├── __init__.py
|
||||
├── db/
|
||||
│ ├── __init__.py
|
||||
│ ├── base.py # SQLAlchemy base
|
||||
│ └── session.py # Database session configuration
|
||||
├── models/
|
||||
│ ├── __init__.py
|
||||
│ └── user.py # User model
|
||||
├── schemas/
|
||||
│ ├── __init__.py
|
||||
│ └── user.py # Pydantic schemas
|
||||
└── crud/
|
||||
├── __init__.py
|
||||
└── user.py # CRUD operations
|
||||
```
|
||||
|
||||
## Installation
|
||||
|
||||
1. Install dependencies:
|
||||
```bash
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
2. Run database migrations:
|
||||
```bash
|
||||
alembic upgrade head
|
||||
```
|
||||
|
||||
3. Start the application:
|
||||
```bash
|
||||
uvicorn main:app --host 0.0.0.0 --port 8000 --reload
|
||||
```
|
||||
|
||||
## API Endpoints
|
||||
|
||||
- `GET /` - Service information
|
||||
- `GET /health` - Health check
|
||||
- `GET /docs` - OpenAPI documentation
|
||||
- `GET /redoc` - Alternative API documentation
|
||||
- `POST /users/` - Create a new user
|
||||
- `GET /users/` - List all users
|
||||
- `GET /users/{user_id}` - Get user by ID
|
||||
- `PUT /users/{user_id}` - Update user
|
||||
- `DELETE /users/{user_id}` - Delete user
|
||||
|
||||
## Database
|
||||
|
||||
The application uses SQLite database stored at `/app/storage/db/db.sqlite`.
|
||||
|
||||
## Environment Variables
|
||||
|
||||
No environment variables are required for basic operation. The application uses SQLite with default settings.
|
||||
|
||||
## Development
|
||||
|
||||
To run the application in development mode:
|
||||
|
||||
```bash
|
||||
uvicorn main:app --reload
|
||||
```
|
||||
|
||||
The API will be available at `http://localhost:8000` with automatic reload on code changes.
|
||||
|
42
alembic.ini
Normal file
42
alembic.ini
Normal file
@ -0,0 +1,42 @@
|
||||
[alembic]
|
||||
script_location = alembic
|
||||
prepend_sys_path = .
|
||||
version_path_separator = os
|
||||
sqlalchemy.url = sqlite:////app/storage/db/db.sqlite
|
||||
version_locations = %(here)s/alembic/versions
|
||||
|
||||
[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"}
|
43
alembic/versions/001_initial_migration.py
Normal file
43
alembic/versions/001_initial_migration.py
Normal file
@ -0,0 +1,43 @@
|
||||
"""Initial migration
|
||||
|
||||
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:
|
||||
# Create users table
|
||||
op.create_table(
|
||||
"users",
|
||||
sa.Column("id", sa.Integer(), nullable=False),
|
||||
sa.Column("email", sa.String(), nullable=False),
|
||||
sa.Column("name", sa.String(), nullable=False),
|
||||
sa.Column("is_active", sa.Boolean(), 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_users_email"), "users", ["email"], unique=True)
|
||||
op.create_index(op.f("ix_users_id"), "users", ["id"], unique=False)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_index(op.f("ix_users_id"), table_name="users")
|
||||
op.drop_index(op.f("ix_users_email"), table_name="users")
|
||||
op.drop_table("users")
|
1
app/__init__.py
Normal file
1
app/__init__.py
Normal file
@ -0,0 +1 @@
|
||||
# FastAPI REST API Service
|
1
app/crud/__init__.py
Normal file
1
app/crud/__init__.py
Normal file
@ -0,0 +1 @@
|
||||
# CRUD module
|
43
app/crud/user.py
Normal file
43
app/crud/user.py
Normal file
@ -0,0 +1,43 @@
|
||||
from sqlalchemy.orm import Session
|
||||
from app.models.user import User
|
||||
from app.schemas.user import UserCreate
|
||||
|
||||
|
||||
def get_user(db: Session, user_id: int):
|
||||
return db.query(User).filter(User.id == user_id).first()
|
||||
|
||||
|
||||
def get_user_by_email(db: Session, email: str):
|
||||
return db.query(User).filter(User.email == email).first()
|
||||
|
||||
|
||||
def get_users(db: Session, skip: int = 0, limit: int = 100):
|
||||
return db.query(User).offset(skip).limit(limit).all()
|
||||
|
||||
|
||||
def create_user(db: Session, user: UserCreate):
|
||||
db_user = User(**user.dict())
|
||||
db.add(db_user)
|
||||
db.commit()
|
||||
db.refresh(db_user)
|
||||
return db_user
|
||||
|
||||
|
||||
def update_user(db: Session, user_id: int, user: UserCreate):
|
||||
db_user = db.query(User).filter(User.id == user_id).first()
|
||||
if db_user:
|
||||
update_data = user.dict(exclude_unset=True)
|
||||
for field, value in update_data.items():
|
||||
setattr(db_user, field, value)
|
||||
db.commit()
|
||||
db.refresh(db_user)
|
||||
return db_user
|
||||
|
||||
|
||||
def delete_user(db: Session, user_id: int):
|
||||
db_user = db.query(User).filter(User.id == user_id).first()
|
||||
if db_user:
|
||||
db.delete(db_user)
|
||||
db.commit()
|
||||
return True
|
||||
return False
|
1
app/db/__init__.py
Normal file
1
app/db/__init__.py
Normal file
@ -0,0 +1 @@
|
||||
# Database module
|
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()
|
14
app/db/session.py
Normal file
14
app/db/session.py
Normal file
@ -0,0 +1,14 @@
|
||||
from sqlalchemy import create_engine
|
||||
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)
|
1
app/models/__init__.py
Normal file
1
app/models/__init__.py
Normal file
@ -0,0 +1 @@
|
||||
# Models module
|
14
app/models/user.py
Normal file
14
app/models/user.py
Normal file
@ -0,0 +1,14 @@
|
||||
from sqlalchemy import Column, Integer, String, DateTime, Boolean
|
||||
from sqlalchemy.sql import func
|
||||
from app.db.base import Base
|
||||
|
||||
|
||||
class User(Base):
|
||||
__tablename__ = "users"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
email = Column(String, unique=True, index=True, nullable=False)
|
||||
name = Column(String, nullable=False)
|
||||
is_active = Column(Boolean, default=True)
|
||||
created_at = Column(DateTime(timezone=True), server_default=func.now())
|
||||
updated_at = Column(DateTime(timezone=True), onupdate=func.now())
|
1
app/schemas/__init__.py
Normal file
1
app/schemas/__init__.py
Normal file
@ -0,0 +1 @@
|
||||
# Schemas module
|
22
app/schemas/user.py
Normal file
22
app/schemas/user.py
Normal file
@ -0,0 +1,22 @@
|
||||
from pydantic import BaseModel, EmailStr
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
|
||||
class UserBase(BaseModel):
|
||||
email: EmailStr
|
||||
name: str
|
||||
is_active: bool = True
|
||||
|
||||
|
||||
class UserCreate(UserBase):
|
||||
pass
|
||||
|
||||
|
||||
class UserResponse(UserBase):
|
||||
id: int
|
||||
created_at: datetime
|
||||
updated_at: Optional[datetime] = None
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
98
main.py
Normal file
98
main.py
Normal file
@ -0,0 +1,98 @@
|
||||
from fastapi import FastAPI, HTTPException, Depends
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.db.session import SessionLocal, engine
|
||||
from app.db.base import Base
|
||||
from app.schemas.user import UserCreate, UserResponse
|
||||
from app.crud.user import create_user, get_user, get_users, update_user, delete_user
|
||||
|
||||
# Create database tables
|
||||
Base.metadata.create_all(bind=engine)
|
||||
|
||||
app = FastAPI(
|
||||
title="REST API Service",
|
||||
description="A REST API service built with FastAPI and SQLite",
|
||||
version="1.0.0",
|
||||
docs_url="/docs",
|
||||
redoc_url="/redoc",
|
||||
openapi_url="/openapi.json",
|
||||
)
|
||||
|
||||
# CORS middleware
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
|
||||
# Dependency to get database session
|
||||
def get_db():
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
@app.get("/")
|
||||
async def root():
|
||||
return {
|
||||
"title": "REST API Service",
|
||||
"description": "A REST API service built with FastAPI and SQLite",
|
||||
"documentation": "/docs",
|
||||
"health_check": "/health",
|
||||
}
|
||||
|
||||
|
||||
@app.get("/health")
|
||||
async def health_check():
|
||||
return {"status": "healthy", "service": "REST API Service"}
|
||||
|
||||
|
||||
# User endpoints
|
||||
@app.post("/users/", response_model=UserResponse)
|
||||
async def create_user_endpoint(user: UserCreate, db: Session = Depends(get_db)):
|
||||
db_user = create_user(db=db, user=user)
|
||||
return db_user
|
||||
|
||||
|
||||
@app.get("/users/", response_model=list[UserResponse])
|
||||
async def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
|
||||
users = get_users(db, skip=skip, limit=limit)
|
||||
return users
|
||||
|
||||
|
||||
@app.get("/users/{user_id}", response_model=UserResponse)
|
||||
async def read_user(user_id: int, db: Session = Depends(get_db)):
|
||||
db_user = get_user(db, user_id=user_id)
|
||||
if db_user is None:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
return db_user
|
||||
|
||||
|
||||
@app.put("/users/{user_id}", response_model=UserResponse)
|
||||
async def update_user_endpoint(
|
||||
user_id: int, user: UserCreate, db: Session = Depends(get_db)
|
||||
):
|
||||
db_user = update_user(db=db, user_id=user_id, user=user)
|
||||
if db_user is None:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
return db_user
|
||||
|
||||
|
||||
@app.delete("/users/{user_id}")
|
||||
async def delete_user_endpoint(user_id: int, db: Session = Depends(get_db)):
|
||||
success = delete_user(db=db, user_id=user_id)
|
||||
if not success:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
return {"message": "User deleted successfully"}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
|
||||
uvicorn.run(app, host="0.0.0.0", port=8000)
|
6
requirements.txt
Normal file
6
requirements.txt
Normal file
@ -0,0 +1,6 @@
|
||||
fastapi==0.104.1
|
||||
uvicorn[standard]==0.24.0
|
||||
sqlalchemy==2.0.23
|
||||
pydantic[email]==2.5.0
|
||||
alembic==1.13.0
|
||||
ruff==0.1.7
|
Loading…
x
Reference in New Issue
Block a user