Create REST API with FastAPI and SQLite

This commit is contained in:
Automated Action 2025-05-17 22:53:53 +00:00
parent fcfb77da6e
commit ba1f7852b6
25 changed files with 697 additions and 2 deletions

153
README.md
View File

@ -1,3 +1,152 @@
# FastAPI Application # FastAPI REST API
This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform. A modern, fast REST API built with FastAPI and SQLite.
## Features
- FastAPI framework with all its features
- SQLAlchemy ORM
- SQLite database
- Alembic migrations
- Pydantic data validation
- Automatic API documentation with Swagger UI and ReDoc
- CORS middleware
- Health check endpoint
## Project Structure
```
.
├── alembic.ini # Alembic configuration
├── app # Main application package
│ ├── api # API endpoints
│ │ └── v1 # API version 1
│ │ ├── api.py # API router
│ │ └── endpoints # API endpoint modules
│ │ └── items.py # Items API endpoints
│ ├── core # Core modules
│ │ └── config.py # Application settings
│ ├── db # Database modules
│ │ └── database.py # Database connection
│ ├── models # SQLAlchemy models
│ │ ├── base.py # Base model
│ │ └── item.py # Item model
│ ├── schemas # Pydantic schemas
│ │ └── item.py # Item schemas
│ └── services # Business logic
├── main.py # Application entry point
├── migrations # Alembic migrations
│ ├── env.py # Alembic environment
│ ├── README # Alembic README
│ ├── script.py.mako # Migration script template
│ └── versions # Migration versions
│ └── 01_initial_migration.py # Initial migration
└── requirements.txt # Project dependencies
```
## Installation
1. Clone the repository:
```bash
git clone https://your-repository-url.git
cd fastapi-rest-api
```
2. Install dependencies:
```bash
pip install -r requirements.txt
```
3. Set up the database:
```bash
# The database will be automatically created at the configured location
# Make sure the directory exists
mkdir -p /app/storage/db
```
4. Run the migrations:
```bash
alembic upgrade head
```
## Running the API
Start the server with:
```bash
uvicorn main:app --reload
```
The API will be available at [http://localhost:8000](http://localhost:8000).
## API Documentation
- Swagger UI: [http://localhost:8000/docs](http://localhost:8000/docs)
- ReDoc: [http://localhost:8000/redoc](http://localhost:8000/redoc)
## API Endpoints
- `GET /api/v1/items`: Get a list of items
- `POST /api/v1/items`: Create a new item
- `GET /api/v1/items/{item_id}`: Get an item by ID
- `PUT /api/v1/items/{item_id}`: Update an item
- `DELETE /api/v1/items/{item_id}`: Delete an item
- `GET /health`: Check API health
## Usage Examples
### Get list of items
```bash
curl -X 'GET' 'http://localhost:8000/api/v1/items' -H 'accept: application/json'
```
### Create a new item
```bash
curl -X 'POST' \
'http://localhost:8000/api/v1/items' \
-H 'accept: application/json' \
-H 'Content-Type: application/json' \
-d '{
"name": "Example Item",
"description": "This is an example item",
"is_active": true
}'
```
### Get an item by ID
```bash
curl -X 'GET' 'http://localhost:8000/api/v1/items/1' -H 'accept: application/json'
```
### Update an item
```bash
curl -X 'PUT' \
'http://localhost:8000/api/v1/items/1' \
-H 'accept: application/json' \
-H 'Content-Type: application/json' \
-d '{
"name": "Updated Item",
"description": "This item has been updated",
"is_active": true
}'
```
### Delete an item
```bash
curl -X 'DELETE' 'http://localhost:8000/api/v1/items/1' -H 'accept: application/json'
```
### Check API health
```bash
curl -X 'GET' 'http://localhost:8000/health' -H 'accept: application/json'
```

86
alembic.ini Normal file
View File

@ -0,0 +1,86 @@
# A generic, single database configuration.
[alembic]
# path to migration scripts
script_location = migrations
# template used to generate migration files
# file_template = %%(rev)s_%%(slug)s
# timezone to use when rendering the date
# within the migration file as well as the filename.
# string value is passed to dateutil.tz.gettz()
# leave blank for localtime
# 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
# version_locations = %(here)s/bar %(here)s/bat migrations/versions
# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = utf-8
# SQLite URL example
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
# 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

0
app/__init__.py Normal file
View File

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

0
app/api/v1/__init__.py Normal file
View File

6
app/api/v1/api.py Normal file
View File

@ -0,0 +1,6 @@
from fastapi import APIRouter
from app.api.v1.endpoints import items
api_router = APIRouter()
api_router.include_router(items.router, prefix="/items", tags=["items"])

View File

View File

@ -0,0 +1,109 @@
from typing import Any, List, Optional
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app import models, schemas
from app.db.database import get_db
router = APIRouter()
@router.get("/", response_model=List[schemas.Item])
def read_items(
db: Session = Depends(get_db),
skip: int = 0,
limit: int = 100,
name: Optional[str] = None,
) -> Any:
"""
Retrieve items.
"""
if name:
items = (
db.query(models.Item)
.filter(models.Item.name.contains(name))
.offset(skip)
.limit(limit)
.all()
)
else:
items = db.query(models.Item).offset(skip).limit(limit).all()
return items
@router.post("/", response_model=schemas.Item)
def create_item(
*,
db: Session = Depends(get_db),
item_in: schemas.ItemCreate,
) -> Any:
"""
Create new item.
"""
item = models.Item(
name=item_in.name,
description=item_in.description,
is_active=item_in.is_active,
)
db.add(item)
db.commit()
db.refresh(item)
return item
@router.get("/{item_id}", response_model=schemas.Item)
def read_item(
*,
db: Session = Depends(get_db),
item_id: int,
) -> Any:
"""
Get item by ID.
"""
item = db.query(models.Item).filter(models.Item.id == item_id).first()
if not item:
raise HTTPException(status_code=404, detail="Item not found")
return item
@router.put("/{item_id}", response_model=schemas.Item)
def update_item(
*,
db: Session = Depends(get_db),
item_id: int,
item_in: schemas.ItemUpdate,
) -> Any:
"""
Update an item.
"""
item = db.query(models.Item).filter(models.Item.id == item_id).first()
if not item:
raise HTTPException(status_code=404, detail="Item not found")
update_data = item_in.model_dump(exclude_unset=True)
for field, value in update_data.items():
setattr(item, field, value)
db.add(item)
db.commit()
db.refresh(item)
return item
@router.delete("/{item_id}", response_model=None, status_code=204)
def delete_item(
*,
db: Session = Depends(get_db),
item_id: int,
) -> Any:
"""
Delete an item.
"""
item = db.query(models.Item).filter(models.Item.id == item_id).first()
if not item:
raise HTTPException(status_code=404, detail="Item not found")
db.delete(item)
db.commit()
return None

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

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

@ -0,0 +1,31 @@
from pathlib import Path
from typing import List, Union
from pydantic import AnyHttpUrl, field_validator
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
API_V1_STR: str = "/api/v1"
PROJECT_NAME: str = "FastAPI REST API"
# CORS middleware configuration
BACKEND_CORS_ORIGINS: List[AnyHttpUrl] = []
@field_validator("BACKEND_CORS_ORIGINS", mode="before")
def assemble_cors_origins(cls, v: Union[str, List[str]]) -> Union[List[str], str]:
if isinstance(v, str) and not v.startswith("["):
return [i.strip() for i in v.split(",")]
elif isinstance(v, (list, str)):
return v
raise ValueError(v)
# SQLite database configuration
DB_DIR: Path = Path("/app/storage/db")
class Config:
case_sensitive = True
env_file = ".env"
settings = Settings()

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

26
app/db/database.py Normal file
View File

@ -0,0 +1,26 @@
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from app.core.config import settings
# Create database directory if it doesn't exist
settings.DB_DIR.mkdir(parents=True, exist_ok=True)
SQLALCHEMY_DATABASE_URL = f"sqlite:///{settings.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()
# Dependency to get DB session
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()

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

@ -0,0 +1 @@
from app.models.item import Item # noqa: F401

19
app/models/base.py Normal file
View File

@ -0,0 +1,19 @@
from datetime import datetime
from sqlalchemy import Column, DateTime, Integer
from sqlalchemy.ext.declarative import declared_attr
from app.db.database import Base
class BaseModel(Base):
"""Base model for all database models"""
__abstract__ = True
id = Column(Integer, primary_key=True, index=True)
created_at = Column(DateTime, default=datetime.utcnow)
updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
@declared_attr
def __tablename__(cls):
return cls.__name__.lower()

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

@ -0,0 +1,10 @@
from sqlalchemy import Boolean, Column, String, Text
from app.models.base import BaseModel
class Item(BaseModel):
"""Item model for database"""
name = Column(String(255), nullable=False, index=True)
description = Column(Text, nullable=True)
is_active = Column(Boolean, default=True)

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

@ -0,0 +1 @@
from app.schemas.item import Item, ItemCreate, ItemInDB, ItemUpdate # noqa: F401

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

@ -0,0 +1,42 @@
from datetime import datetime
from typing import Optional
from pydantic import BaseModel
class ItemBase(BaseModel):
"""Base schema for Item"""
name: str
description: Optional[str] = None
is_active: bool = True
class ItemCreate(ItemBase):
"""Schema for creating an Item"""
pass
class ItemUpdate(ItemBase):
"""Schema for updating an Item"""
name: Optional[str] = None
is_active: Optional[bool] = None
class ItemInDBBase(ItemBase):
"""Base schema for Item in DB"""
id: int
created_at: datetime
updated_at: datetime
class Config:
from_attributes = True
class Item(ItemInDBBase):
"""Schema for Item response"""
pass
class ItemInDB(ItemInDBBase):
"""Schema for Item in DB (for internal use)"""
pass

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

31
main.py Normal file
View File

@ -0,0 +1,31 @@
from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware
from app.api.v1.api import api_router
from app.core.config import settings
app = FastAPI(
title=settings.PROJECT_NAME,
openapi_url=f"{settings.API_V1_STR}/openapi.json",
version="0.1.0",
)
# Set all CORS enabled origins
if settings.BACKEND_CORS_ORIGINS:
app.add_middleware(
CORSMiddleware,
allow_origins=[str(origin) for origin in settings.BACKEND_CORS_ORIGINS],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.include_router(api_router, prefix=settings.API_V1_STR)
@app.get("/health", tags=["Health"])
async def health():
return {"status": "ok"}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)

1
migrations/README Normal file
View File

@ -0,0 +1 @@
Generic single-database configuration.

79
migrations/env.py Normal file
View File

@ -0,0 +1,79 @@
from logging.config import fileConfig
from alembic import context
from sqlalchemy import engine_from_config, pool
# 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
from app.db.database import Base # noqa: E402
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 = 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:
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
connectable = engine_from_config(
config.get_section(config.config_ini_section),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
with connectable.connect() as connection:
is_sqlite = connection.dialect.name == 'sqlite'
context.configure(
connection=connection,
target_metadata=target_metadata,
render_as_batch=is_sqlite # Key configuration 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
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,38 @@
"""initial migration
Revision ID: 01_initial_migration
Revises:
Create Date: 2023-10-15
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '01_initial_migration'
down_revision = None
branch_labels = None
depends_on = None
def upgrade() -> None:
# Create item table
op.create_table(
'item',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.Column('name', sa.String(length=255), nullable=False),
sa.Column('description', sa.Text(), nullable=True),
sa.Column('is_active', sa.Boolean(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_item_id'), 'item', ['id'], unique=False)
op.create_index(op.f('ix_item_name'), 'item', ['name'], unique=False)
def downgrade() -> None:
# Drop item table
op.drop_index(op.f('ix_item_name'), table_name='item')
op.drop_index(op.f('ix_item_id'), table_name='item')
op.drop_table('item')

33
pyproject.toml Normal file
View File

@ -0,0 +1,33 @@
[tool.ruff]
line-length = 88
target-version = "py39"
exclude = [
".bzr",
".direnv",
".eggs",
".git",
".git-rewrite",
".hg",
".mypy_cache",
".nox",
".pants.d",
".pytype",
".ruff_cache",
".svn",
".tox",
".venv",
"__pypackages__",
"_build",
"buck-out",
"build",
"dist",
"node_modules",
"venv",
]
[tool.ruff.lint]
select = ["E", "F", "I"]
ignore = []
[tool.ruff.lint.isort]
known-third-party = []

9
requirements.txt Normal file
View File

@ -0,0 +1,9 @@
fastapi>=0.103.1
uvicorn>=0.23.2
sqlalchemy>=2.0.20
alembic>=1.12.0
pydantic>=2.3.0
pydantic-settings>=2.0.3
python-dotenv>=1.0.0
ruff>=0.0.287
email-validator>=2.0.0