Create REST API with FastAPI and SQLite

- Set up FastAPI application with CORS and authentication
- Implement user registration and login with JWT tokens
- Create SQLAlchemy models for users and items
- Add CRUD endpoints for item management
- Configure Alembic for database migrations
- Add health check endpoint
- Include comprehensive API documentation
- Set up proper project structure with routers and schemas
This commit is contained in:
Automated Action 2025-07-17 16:54:25 +00:00
parent b1df7d7f6e
commit 10f64177dc
24 changed files with 627 additions and 2 deletions

View File

@ -1,3 +1,67 @@
# FastAPI Application # REST API Service
This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform. A comprehensive REST API built with FastAPI and SQLite, featuring user authentication, CRUD operations, and health monitoring.
## Features
- User registration and authentication with JWT tokens
- Item management (CRUD operations)
- SQLite database with SQLAlchemy ORM
- Database migrations with Alembic
- Health check endpoint
- CORS enabled for all origins
- Interactive API documentation at `/docs` and `/redoc`
- OpenAPI specification at `/openapi.json`
## Installation
1. Install dependencies:
```bash
pip install -r requirements.txt
```
2. Run the application:
```bash
uvicorn main:app --host 0.0.0.0 --port 8000
```
## Environment Variables
Set the following environment variables:
- `SECRET_KEY`: JWT secret key for token signing (required for production)
## API Endpoints
### Authentication
- `POST /auth/register` - Register a new user
- `POST /auth/login` - Login and get access token
- `GET /auth/me` - Get current user profile
### Items
- `GET /items/` - List user's items
- `POST /items/` - Create a new item
- `GET /items/{item_id}` - Get a specific item
- `PUT /items/{item_id}` - Update an item
- `DELETE /items/{item_id}` - Delete an item
### Health
- `GET /health` - Health check endpoint
### Documentation
- `GET /` - Service information
- `GET /docs` - Interactive API documentation
- `GET /redoc` - ReDoc documentation
- `GET /openapi.json` - OpenAPI specification
## Database
The application uses SQLite with database file stored at `/app/storage/db/db.sqlite`.
## Development
The application includes Ruff for code linting and formatting. Run linting with:
```bash
ruff check .
ruff format .
```

41
alembic.ini Normal file
View 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

51
alembic/env.py Normal file
View File

@ -0,0 +1,51 @@
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(os.path.abspath(__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
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() -> None:
${upgrades if upgrades else "pass"}
def downgrade() -> None:
${downgrades if downgrades else "pass"}

View File

@ -0,0 +1,52 @@
"""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('hashed_password', sa.String(), nullable=False),
sa.Column('is_active', sa.Boolean(), nullable=True),
sa.Column('created_at', sa.DateTime(), 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)
# Create items table
op.create_table('items',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('title', sa.String(), nullable=False),
sa.Column('description', sa.Text(), nullable=True),
sa.Column('owner_id', sa.Integer(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['owner_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_items_id'), 'items', ['id'], unique=False)
op.create_index(op.f('ix_items_title'), 'items', ['title'], unique=False)
def downgrade() -> None:
op.drop_index(op.f('ix_items_title'), table_name='items')
op.drop_index(op.f('ix_items_id'), table_name='items')
op.drop_table('items')
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')

0
app/__init__.py Normal file
View File

0
app/core/__init__.py Normal file
View File

43
app/core/auth.py Normal file
View File

@ -0,0 +1,43 @@
from datetime import datetime, timedelta
from typing import Optional
from jose import JWTError, jwt
from passlib.context import CryptContext
from fastapi import HTTPException, status
from app.core.config import settings
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
def verify_password(plain_password: str, hashed_password: str) -> bool:
return pwd_context.verify(plain_password, hashed_password)
def get_password_hash(password: str) -> str:
return pwd_context.hash(password)
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):
to_encode = data.copy()
if expires_delta:
expire = datetime.utcnow() + expires_delta
else:
expire = datetime.utcnow() + timedelta(minutes=settings.access_token_expire_minutes)
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(to_encode, settings.secret_key, algorithm=settings.algorithm)
return encoded_jwt
def verify_token(token: str) -> Optional[str]:
try:
payload = jwt.decode(token, settings.secret_key, algorithms=[settings.algorithm])
email: str = payload.get("sub")
if email is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
return email
except JWTError:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)

12
app/core/config.py Normal file
View File

@ -0,0 +1,12 @@
import os
from pydantic import BaseSettings
class Settings(BaseSettings):
secret_key: str = os.getenv("SECRET_KEY", "your-secret-key-here")
algorithm: str = "HS256"
access_token_expire_minutes: int = 30
class Config:
env_file = ".env"
settings = Settings()

0
app/db/__init__.py Normal file
View File

3
app/db/base.py Normal file
View File

@ -0,0 +1,3 @@
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()

22
app/db/session.py Normal file
View File

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

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

16
app/models/item.py Normal file
View File

@ -0,0 +1,16 @@
from sqlalchemy import Column, Integer, String, Text, ForeignKey, DateTime
from sqlalchemy.orm import relationship
from datetime import datetime
from app.db.base import Base
class Item(Base):
__tablename__ = "items"
id = Column(Integer, primary_key=True, index=True)
title = Column(String, index=True, nullable=False)
description = Column(Text, nullable=True)
owner_id = Column(Integer, ForeignKey("users.id"), nullable=False)
created_at = Column(DateTime, default=datetime.utcnow)
updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
owner = relationship("User", back_populates="items")

15
app/models/user.py Normal file
View File

@ -0,0 +1,15 @@
from sqlalchemy import Column, Integer, String, Boolean, DateTime
from sqlalchemy.orm import relationship
from datetime import datetime
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)
hashed_password = Column(String, nullable=False)
is_active = Column(Boolean, default=True)
created_at = Column(DateTime, default=datetime.utcnow)
items = relationship("Item", back_populates="owner")

0
app/routers/__init__.py Normal file
View File

72
app/routers/auth.py Normal file
View File

@ -0,0 +1,72 @@
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from sqlalchemy.orm import Session
from datetime import timedelta
from app.db.session import get_db
from app.models.user import User
from app.schemas.user import UserCreate, UserLogin, Token, User as UserSchema
from app.core.auth import verify_password, get_password_hash, create_access_token, verify_token
from app.core.config import settings
router = APIRouter()
security = HTTPBearer()
def get_user_by_email(db: Session, email: str):
return db.query(User).filter(User.email == email).first()
def create_user(db: Session, user: UserCreate):
hashed_password = get_password_hash(user.password)
db_user = User(email=user.email, hashed_password=hashed_password)
db.add(db_user)
db.commit()
db.refresh(db_user)
return db_user
def authenticate_user(db: Session, email: str, password: str):
user = get_user_by_email(db, email)
if not user:
return False
if not verify_password(password, user.hashed_password):
return False
return user
def get_current_user(credentials: HTTPAuthorizationCredentials = Depends(security), db: Session = Depends(get_db)):
email = verify_token(credentials.credentials)
user = get_user_by_email(db, email)
if user is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
return user
@router.post("/register", response_model=UserSchema)
def register(user: UserCreate, db: Session = Depends(get_db)):
db_user = get_user_by_email(db, user.email)
if db_user:
raise HTTPException(
status_code=400,
detail="Email already registered"
)
return create_user(db, user)
@router.post("/login", response_model=Token)
def login(user_credentials: UserLogin, db: Session = Depends(get_db)):
user = authenticate_user(db, user_credentials.email, user_credentials.password)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect email or password",
headers={"WWW-Authenticate": "Bearer"},
)
access_token_expires = timedelta(minutes=settings.access_token_expire_minutes)
access_token = create_access_token(
data={"sub": user.email}, expires_delta=access_token_expires
)
return {"access_token": access_token, "token_type": "bearer"}
@router.get("/me", response_model=UserSchema)
def read_users_me(current_user: User = Depends(get_current_user)):
return current_user

27
app/routers/health.py Normal file
View File

@ -0,0 +1,27 @@
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from sqlalchemy import text
from app.db.session import get_db
import os
router = APIRouter()
@router.get("/health")
def health_check(db: Session = Depends(get_db)):
try:
# Check database connectivity
db.execute(text("SELECT 1"))
db_status = "healthy"
except Exception as e:
db_status = f"unhealthy: {str(e)}"
# Check if storage directory exists
storage_path = "/app/storage"
storage_status = "healthy" if os.path.exists(storage_path) else "storage directory not found"
return {
"status": "healthy" if db_status == "healthy" and storage_status == "healthy" else "unhealthy",
"database": db_status,
"storage": storage_status,
"service": "REST API Service"
}

76
app/routers/items.py Normal file
View File

@ -0,0 +1,76 @@
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.item import Item
from app.models.user import User
from app.schemas.item import ItemCreate, ItemUpdate, Item as ItemSchema
from app.routers.auth import get_current_user
router = APIRouter()
def get_items(db: Session, user_id: int, skip: int = 0, limit: int = 100):
return db.query(Item).filter(Item.owner_id == user_id).offset(skip).limit(limit).all()
def get_item(db: Session, item_id: int, user_id: int):
return db.query(Item).filter(Item.id == item_id, Item.owner_id == user_id).first()
def create_item(db: Session, item: ItemCreate, user_id: int):
db_item = Item(**item.dict(), owner_id=user_id)
db.add(db_item)
db.commit()
db.refresh(db_item)
return db_item
def update_item(db: Session, item_id: int, item_update: ItemUpdate, user_id: int):
db_item = db.query(Item).filter(Item.id == item_id, Item.owner_id == user_id).first()
if not db_item:
return None
update_data = item_update.dict(exclude_unset=True)
for field, value in update_data.items():
setattr(db_item, field, value)
db.commit()
db.refresh(db_item)
return db_item
def delete_item(db: Session, item_id: int, user_id: int):
db_item = db.query(Item).filter(Item.id == item_id, Item.owner_id == user_id).first()
if not db_item:
return None
db.delete(db_item)
db.commit()
return db_item
@router.get("/", response_model=List[ItemSchema])
def read_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
items = get_items(db, current_user.id, skip=skip, limit=limit)
return items
@router.post("/", response_model=ItemSchema)
def create_item_endpoint(item: ItemCreate, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
return create_item(db, item, current_user.id)
@router.get("/{item_id}", response_model=ItemSchema)
def read_item(item_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
db_item = get_item(db, item_id, current_user.id)
if db_item is None:
raise HTTPException(status_code=404, detail="Item not found")
return db_item
@router.put("/{item_id}", response_model=ItemSchema)
def update_item_endpoint(item_id: int, item_update: ItemUpdate, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
db_item = update_item(db, item_id, item_update, current_user.id)
if db_item is None:
raise HTTPException(status_code=404, detail="Item not found")
return db_item
@router.delete("/{item_id}", response_model=ItemSchema)
def delete_item_endpoint(item_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
db_item = delete_item(db, item_id, current_user.id)
if db_item is None:
raise HTTPException(status_code=404, detail="Item not found")
return db_item

0
app/schemas/__init__.py Normal file
View File

23
app/schemas/item.py Normal file
View File

@ -0,0 +1,23 @@
from pydantic import BaseModel
from datetime import datetime
from typing import Optional
class ItemBase(BaseModel):
title: str
description: Optional[str] = None
class ItemCreate(ItemBase):
pass
class ItemUpdate(BaseModel):
title: Optional[str] = None
description: Optional[str] = None
class Item(ItemBase):
id: int
owner_id: int
created_at: datetime
updated_at: datetime
class Config:
from_attributes = True

28
app/schemas/user.py Normal file
View File

@ -0,0 +1,28 @@
from pydantic import BaseModel, EmailStr
from datetime import datetime
from typing import Optional
class UserBase(BaseModel):
email: EmailStr
class UserCreate(UserBase):
password: str
class UserLogin(BaseModel):
email: EmailStr
password: str
class User(UserBase):
id: int
is_active: bool
created_at: datetime
class Config:
from_attributes = True
class Token(BaseModel):
access_token: str
token_type: str
class TokenData(BaseModel):
email: Optional[str] = None

47
main.py Normal file
View File

@ -0,0 +1,47 @@
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from contextlib import asynccontextmanager
from app.db.session import engine
from app.db.base import Base
from app.routers import auth, items, health
@asynccontextmanager
async def lifespan(app: FastAPI):
# Create database tables
Base.metadata.create_all(bind=engine)
yield
app = FastAPI(
title="REST API Service",
description="A comprehensive REST API built with FastAPI and SQLite",
version="1.0.0",
lifespan=lifespan,
openapi_url="/openapi.json"
)
# Add CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Include routers
app.include_router(auth.router, prefix="/auth", tags=["authentication"])
app.include_router(items.router, prefix="/items", tags=["items"])
app.include_router(health.router, tags=["health"])
@app.get("/")
async def root():
return {
"title": "REST API Service",
"documentation": "/docs",
"health_check": "/health"
}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)

9
requirements.txt Normal file
View File

@ -0,0 +1,9 @@
fastapi==0.104.1
uvicorn==0.24.0
sqlalchemy==2.0.23
alembic==1.13.0
pydantic==2.5.0
python-multipart==0.0.6
passlib[bcrypt]==1.7.4
python-jose[cryptography]==3.3.0
ruff==0.1.6