Create Calculator API with FastAPI
Implemented: - Basic arithmetic operations (add, subtract, multiply, divide) - Input validation - SQLite database with SQLAlchemy - Alembic migrations - Health endpoint generated with BackendIM... (backend.im)
This commit is contained in:
parent
a8f66137df
commit
5ca82943e6
44
README.md
44
README.md
@ -1,3 +1,43 @@
|
||||
# FastAPI Application
|
||||
# Calculator API
|
||||
|
||||
This is a FastAPI application bootstrapped by BackendIM, the AI-powered backend generation platform.
|
||||
This is a FastAPI-based calculator API that provides basic arithmetic operations.
|
||||
|
||||
## Features
|
||||
|
||||
- Basic arithmetic operations: addition, subtraction, multiplication, division
|
||||
- Input validation
|
||||
- Results stored in SQLite database
|
||||
- Health check endpoint
|
||||
- OpenAPI documentation
|
||||
|
||||
## API Endpoints
|
||||
|
||||
- `GET /health`: Health check endpoint
|
||||
- `POST /api/add`: Add two numbers
|
||||
- `POST /api/subtract`: Subtract second number from first number
|
||||
- `POST /api/multiply`: Multiply two numbers
|
||||
- `POST /api/divide`: Divide first number by second number
|
||||
|
||||
## Setup and Running
|
||||
|
||||
1. Install dependencies:
|
||||
```
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
2. Run the application:
|
||||
```
|
||||
uvicorn main:app --reload
|
||||
```
|
||||
|
||||
3. Access the API documentation:
|
||||
- Swagger UI: http://localhost:8000/docs
|
||||
- ReDoc: http://localhost:8000/redoc
|
||||
|
||||
## Database
|
||||
|
||||
The application uses SQLite as the database, storing calculation history. The database file is located at `/app/storage/db/db.sqlite`.
|
||||
|
||||
## Migrations
|
||||
|
||||
Database migrations are managed with Alembic.
|
84
alembic.ini
Normal file
84
alembic.ini
Normal file
@ -0,0 +1,84 @@
|
||||
# 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
|
||||
|
||||
# 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 alembic/versions. When using multiple version
|
||||
# directories, initial revisions must be specified with --version-path
|
||||
# version_locations = %(here)s/bar %(here)s/bat alembic/versions
|
||||
|
||||
# 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
|
||||
|
||||
# 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
|
83
alembic/env.py
Normal file
83
alembic/env.py
Normal file
@ -0,0 +1,83 @@
|
||||
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 main import Base
|
||||
|
||||
# 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.
|
||||
fileConfig(config.config_file_name)
|
||||
|
||||
# add your model's MetaData object here
|
||||
# for 'autogenerate' support
|
||||
# from myapp import mymodel
|
||||
# target_metadata = mymodel.Base.metadata
|
||||
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():
|
||||
"""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():
|
||||
"""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
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():
|
||||
${upgrades if upgrades else "pass"}
|
||||
|
||||
|
||||
def downgrade():
|
||||
${downgrades if downgrades else "pass"}
|
36
alembic/versions/d29a9efb00af_initial_migration.py
Normal file
36
alembic/versions/d29a9efb00af_initial_migration.py
Normal file
@ -0,0 +1,36 @@
|
||||
"""Initial migration
|
||||
|
||||
Revision ID: d29a9efb00af
|
||||
Revises:
|
||||
Create Date: 2025-05-14 00:00:00.000000
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'd29a9efb00af'
|
||||
down_revision = None
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.create_table('calculations',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('operation', sa.String(), nullable=False),
|
||||
sa.Column('num1', sa.Float(), nullable=False),
|
||||
sa.Column('num2', sa.Float(), nullable=True),
|
||||
sa.Column('result', sa.Float(), nullable=False),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
op.create_index(op.f('ix_calculations_id'), 'calculations', ['id'], unique=False)
|
||||
op.create_index(op.f('ix_calculations_operation'), 'calculations', ['operation'], unique=False)
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.drop_index(op.f('ix_calculations_operation'), table_name='calculations')
|
||||
op.drop_index(op.f('ix_calculations_id'), table_name='calculations')
|
||||
op.drop_table('calculations')
|
165
main.py
Normal file
165
main.py
Normal file
@ -0,0 +1,165 @@
|
||||
from fastapi import FastAPI, HTTPException, Depends
|
||||
from fastapi.responses import JSONResponse
|
||||
from pydantic import BaseModel, Field
|
||||
from typing import Optional
|
||||
from pathlib import Path
|
||||
from sqlalchemy import create_engine, Column, Integer, Float, String, DateTime
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
from sqlalchemy.orm import sessionmaker, Session
|
||||
import datetime
|
||||
|
||||
app = FastAPI(
|
||||
title="Calculator API",
|
||||
description="A simple calculator API with basic operations",
|
||||
version="1.0.0"
|
||||
)
|
||||
|
||||
# Database setup
|
||||
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()
|
||||
|
||||
# Database models
|
||||
class Calculation(Base):
|
||||
__tablename__ = "calculations"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
operation = Column(String, index=True)
|
||||
num1 = Column(Float)
|
||||
num2 = Column(Float, nullable=True)
|
||||
result = Column(Float)
|
||||
created_at = Column(DateTime, default=datetime.datetime.utcnow)
|
||||
|
||||
# Create tables
|
||||
Base.metadata.create_all(bind=engine)
|
||||
|
||||
# Dependency
|
||||
def get_db():
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
# Input models
|
||||
class CalculationBase(BaseModel):
|
||||
num1: float = Field(..., description="First number")
|
||||
num2: float = Field(..., description="Second number")
|
||||
|
||||
class CalculationResponse(BaseModel):
|
||||
result: float = Field(..., description="Result of the calculation")
|
||||
operation: str = Field(..., description="Operation performed")
|
||||
num1: float = Field(..., description="First number")
|
||||
num2: float = Field(..., description="Second number")
|
||||
|
||||
class Config:
|
||||
orm_mode = True
|
||||
|
||||
# Health check endpoint
|
||||
@app.get("/health", tags=["Health"])
|
||||
async def health():
|
||||
return {"status": "healthy"}
|
||||
|
||||
# Calculator endpoints
|
||||
@app.post("/api/add", response_model=CalculationResponse, tags=["Calculator"])
|
||||
async def add(data: CalculationBase, db: Session = Depends(get_db)):
|
||||
result = data.num1 + data.num2
|
||||
|
||||
# Save to database
|
||||
db_calc = Calculation(
|
||||
operation="add",
|
||||
num1=data.num1,
|
||||
num2=data.num2,
|
||||
result=result
|
||||
)
|
||||
db.add(db_calc)
|
||||
db.commit()
|
||||
db.refresh(db_calc)
|
||||
|
||||
return {
|
||||
"result": result,
|
||||
"operation": "add",
|
||||
"num1": data.num1,
|
||||
"num2": data.num2
|
||||
}
|
||||
|
||||
@app.post("/api/subtract", response_model=CalculationResponse, tags=["Calculator"])
|
||||
async def subtract(data: CalculationBase, db: Session = Depends(get_db)):
|
||||
result = data.num1 - data.num2
|
||||
|
||||
# Save to database
|
||||
db_calc = Calculation(
|
||||
operation="subtract",
|
||||
num1=data.num1,
|
||||
num2=data.num2,
|
||||
result=result
|
||||
)
|
||||
db.add(db_calc)
|
||||
db.commit()
|
||||
db.refresh(db_calc)
|
||||
|
||||
return {
|
||||
"result": result,
|
||||
"operation": "subtract",
|
||||
"num1": data.num1,
|
||||
"num2": data.num2
|
||||
}
|
||||
|
||||
@app.post("/api/multiply", response_model=CalculationResponse, tags=["Calculator"])
|
||||
async def multiply(data: CalculationBase, db: Session = Depends(get_db)):
|
||||
result = data.num1 * data.num2
|
||||
|
||||
# Save to database
|
||||
db_calc = Calculation(
|
||||
operation="multiply",
|
||||
num1=data.num1,
|
||||
num2=data.num2,
|
||||
result=result
|
||||
)
|
||||
db.add(db_calc)
|
||||
db.commit()
|
||||
db.refresh(db_calc)
|
||||
|
||||
return {
|
||||
"result": result,
|
||||
"operation": "multiply",
|
||||
"num1": data.num1,
|
||||
"num2": data.num2
|
||||
}
|
||||
|
||||
@app.post("/api/divide", response_model=CalculationResponse, tags=["Calculator"])
|
||||
async def divide(data: CalculationBase, db: Session = Depends(get_db)):
|
||||
if data.num2 == 0:
|
||||
raise HTTPException(status_code=400, detail="Cannot divide by zero")
|
||||
|
||||
result = data.num1 / data.num2
|
||||
|
||||
# Save to database
|
||||
db_calc = Calculation(
|
||||
operation="divide",
|
||||
num1=data.num1,
|
||||
num2=data.num2,
|
||||
result=result
|
||||
)
|
||||
db.add(db_calc)
|
||||
db.commit()
|
||||
db.refresh(db_calc)
|
||||
|
||||
return {
|
||||
"result": result,
|
||||
"operation": "divide",
|
||||
"num1": data.num1,
|
||||
"num2": data.num2
|
||||
}
|
||||
|
||||
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.68.0
|
||||
uvicorn>=0.15.0
|
||||
sqlalchemy>=1.4.23
|
||||
pydantic>=1.8.2
|
||||
alembic>=1.7.1
|
||||
ruff>=0.0.171
|
Loading…
x
Reference in New Issue
Block a user