Create Calculator API with FastAPI and SQLAlchemy

- Setup FastAPI project structure
- Add database models for calculations
- Create API endpoints for basic math operations
- Add health endpoint
- Configure SQLite and Alembic for database management
- Update README with usage instructions

generated with BackendIM... (backend.im)
This commit is contained in:
Automated Action 2025-05-13 22:57:26 +00:00
parent b02e6e936f
commit 3efcd88ffa
27 changed files with 576 additions and 2 deletions

101
README.md
View File

@ -1,3 +1,100 @@
# FastAPI Application
# Calculator API
This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform.
A simple calculator API built with FastAPI and SQLAlchemy that performs basic arithmetic operations and stores calculation history.
## Features
- Basic arithmetic operations (add, subtract, multiply, divide)
- Square root calculation
- Calculation history storage in SQLite database
- Health check endpoint
## API Endpoints
### Calculator Operations
- `POST /api/v1/calculator/` - Perform a calculation
- `GET /api/v1/calculator/history` - Get calculation history
- `GET /api/v1/calculator/{calculation_id}` - Get a specific calculation
### Health Check
- `GET /api/v1/health` - API health status
## Installation
```bash
# Clone the repository
git clone <repository-url>
# Install dependencies
pip install -r requirements.txt
# Run migrations
alembic upgrade head
# Start the API
uvicorn main:app --reload
```
## Environment Variables
Create a `.env` file in the root directory with the following variables:
```
# No environment variables required for basic setup
```
## API Documentation
Once the API is running, you can access the API documentation at:
- Swagger UI: `http://localhost:8000/docs`
- ReDoc: `http://localhost:8000/redoc`
## Example Usage
### Perform Addition
```json
POST /api/v1/calculator/
{
"operation": "add",
"first_number": 5,
"second_number": 3
}
```
Response:
```json
{
"id": 1,
"operation": "add",
"first_number": 5,
"second_number": 3,
"result": 8,
"created_at": "2025-05-13T12:00:00.000Z"
}
```
### Perform Square Root
```json
POST /api/v1/calculator/
{
"operation": "square_root",
"first_number": 16
}
```
Response:
```json
{
"id": 2,
"operation": "square_root",
"first_number": 16,
"second_number": null,
"result": 4,
"created_at": "2025-05-13T12:01:00.000Z"
}
```

106
alembic.ini Normal file
View File

@ -0,0 +1,106 @@
# A generic, single database configuration.
[alembic]
# path to migration scripts
script_location = alembic
# template used to generate migration files
# file_template = %%(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 `alembic[tz]` to the pip requirements
# 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 alembic/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:alembic/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 for new projects.
# set to 'true' to search source files recursively
# in each "version_locations" directory
# new in Alembic version 1.10
# recursive_version_locations = false
# 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
alembic/README Normal file
View File

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

77
alembic/env.py Normal file
View File

@ -0,0 +1,77 @@
from logging.config import fileConfig
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from alembic import context
# 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.base import Base
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:
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,38 @@
"""initial setup
Revision ID: 001
Revises:
Create Date: 2025-05-13
"""
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 calculation table
op.create_table(
'calculation',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('operation', sa.String(), nullable=False),
sa.Column('first_number', sa.Float(), nullable=False),
sa.Column('second_number', sa.Float(), nullable=True),
sa.Column('result', sa.Float(), nullable=False),
sa.Column('created_at', sa.DateTime(timezone=True), server_default=sa.text('CURRENT_TIMESTAMP'), nullable=False),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_calculation_id'), 'calculation', ['id'], unique=False)
op.create_index(op.f('ix_calculation_operation'), 'calculation', ['operation'], unique=False)
def downgrade() -> None:
op.drop_index(op.f('ix_calculation_operation'), table_name='calculation')
op.drop_index(op.f('ix_calculation_id'), table_name='calculation')
op.drop_table('calculation')

View File

0
app/__init__.py Normal file
View File

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

View File

View File

@ -0,0 +1,76 @@
import math
from typing import List
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app.db.session import get_db
from app.schemas.calculation import CalculationCreate, CalculationResponse
from app.crud import calculation
router = APIRouter()
def perform_calculation(calc: CalculationCreate) -> float:
"""Perform the calculation based on the operation and numbers provided."""
if calc.operation == "add":
if calc.second_number is None:
raise HTTPException(status_code=400, detail="Second number is required for addition")
return calc.first_number + calc.second_number
elif calc.operation == "subtract":
if calc.second_number is None:
raise HTTPException(status_code=400, detail="Second number is required for subtraction")
return calc.first_number - calc.second_number
elif calc.operation == "multiply":
if calc.second_number is None:
raise HTTPException(status_code=400, detail="Second number is required for multiplication")
return calc.first_number * calc.second_number
elif calc.operation == "divide":
if calc.second_number is None:
raise HTTPException(status_code=400, detail="Second number is required for division")
if calc.second_number == 0:
raise HTTPException(status_code=400, detail="Cannot divide by zero")
return calc.first_number / calc.second_number
elif calc.operation == "square_root":
if calc.first_number < 0:
raise HTTPException(status_code=400, detail="Cannot calculate square root of a negative number")
return math.sqrt(calc.first_number)
else:
raise HTTPException(
status_code=400,
detail="Invalid operation. Supported operations: add, subtract, multiply, divide, square_root"
)
@router.post("/", response_model=CalculationResponse)
def calculate(calc: CalculationCreate, db: Session = Depends(get_db)):
"""
Perform a calculation and store it in the database.
- **operation**: add, subtract, multiply, divide, or square_root
- **first_number**: First operand
- **second_number**: Second operand (not required for square_root)
"""
result = perform_calculation(calc)
db_calc = calculation.create_calculation(db=db, calc=calc, result=result)
return db_calc
@router.get("/history", response_model=List[CalculationResponse])
def get_calculation_history(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
"""
Retrieve calculation history.
"""
calcs = calculation.get_calculations(db, skip=skip, limit=limit)
return calcs
@router.get("/{calculation_id}", response_model=CalculationResponse)
def get_calculation_by_id(calculation_id: int, db: Session = Depends(get_db)):
"""
Retrieve a specific calculation by ID.
"""
db_calc = calculation.get_calculation(db, calculation_id=calculation_id)
if db_calc is None:
raise HTTPException(status_code=404, detail="Calculation not found")
return db_calc

View File

@ -0,0 +1,25 @@
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from app.db.session import get_db
router = APIRouter()
@router.get("/health")
def health_check(db: Session = Depends(get_db)):
"""
Health check endpoint for the API.
Returns status of the API and database connectivity.
"""
# Check database connection
try:
# Execute a simple query to verify database connectivity
db.execute("SELECT 1")
db_status = "healthy"
except Exception as e:
db_status = f"unhealthy: {str(e)}"
return {
"status": "healthy",
"database": db_status,
"version": "1.0.0"
}

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

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

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

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

@ -0,0 +1,17 @@
from pathlib import Path
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
API_V1_STR: str = "/api/v1"
PROJECT_NAME: str = "Calculator API"
# Database settings
DB_DIR = Path("/app") / "storage" / "db"
DB_DIR.mkdir(parents=True, exist_ok=True)
DATABASE_URL: str = f"sqlite:///{DB_DIR}/db.sqlite"
class Config:
env_file = ".env"
case_sensitive = True
settings = Settings()

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

21
app/crud/calculation.py Normal file
View File

@ -0,0 +1,21 @@
from sqlalchemy.orm import Session
from app.models.calculation import Calculation
from app.schemas.calculation import CalculationCreate
def create_calculation(db: Session, calc: CalculationCreate, result: float) -> Calculation:
db_calculation = Calculation(
operation=calc.operation,
first_number=calc.first_number,
second_number=calc.second_number,
result=result
)
db.add(db_calculation)
db.commit()
db.refresh(db_calculation)
return db_calculation
def get_calculations(db: Session, skip: int = 0, limit: int = 100):
return db.query(Calculation).order_by(Calculation.created_at.desc()).offset(skip).limit(limit).all()
def get_calculation(db: Session, calculation_id: int):
return db.query(Calculation).filter(Calculation.id == calculation_id).first()

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

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

@ -0,0 +1,2 @@
from app.db.base_class import Base
from app.models.calculation import Calculation

11
app/db/base_class.py Normal file
View File

@ -0,0 +1,11 @@
from typing import Any
from sqlalchemy.ext.declarative import as_declarative, declared_attr
@as_declarative()
class Base:
id: Any
__name__: str
@declared_attr
def __tablename__(cls) -> str:
return cls.__name__.lower()

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

@ -0,0 +1,22 @@
from pathlib import Path
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
# Create DB directory
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

11
app/models/calculation.py Normal file
View File

@ -0,0 +1,11 @@
from sqlalchemy import Column, Integer, String, Float, DateTime
from sqlalchemy.sql import func
from app.db.base_class import Base
class Calculation(Base):
id = Column(Integer, primary_key=True, index=True)
operation = Column(String, index=True)
first_number = Column(Float)
second_number = Column(Float, nullable=True)
result = Column(Float)
created_at = Column(DateTime(timezone=True), server_default=func.now())

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

View File

@ -0,0 +1,19 @@
from datetime import datetime
from typing import Optional
from pydantic import BaseModel, Field
class CalculationBase(BaseModel):
operation: str = Field(..., description="Mathematical operation: add, subtract, multiply, divide, or square_root")
first_number: float = Field(..., description="First operand")
second_number: Optional[float] = Field(None, description="Second operand (not required for square_root)")
class CalculationCreate(CalculationBase):
pass
class CalculationResponse(CalculationBase):
id: int
result: float
created_at: datetime
class Config:
orm_mode = True

14
main.py Normal file
View File

@ -0,0 +1,14 @@
import uvicorn
from fastapi import FastAPI
from app.api.router import router as api_router
from app.core.config import settings
app = FastAPI(
title=settings.PROJECT_NAME,
openapi_url=f"{settings.API_V1_STR}/openapi.json",
)
app.include_router(api_router, prefix=settings.API_V1_STR)
if __name__ == "__main__":
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)

7
requirements.txt Normal file
View File

@ -0,0 +1,7 @@
fastapi==0.110.1
uvicorn==0.29.0
sqlalchemy==2.0.29
pydantic==2.6.4
alembic==1.13.1
ruff==0.3.2
python-dotenv==1.0.1