Implement Number Divisibility API with FastAPI and SQLite
This commit is contained in:
parent
2d0237b831
commit
930e84fc96
29
README.md
29
README.md
@ -5,6 +5,9 @@ A simple REST API built with FastAPI that checks if a number is divisible by 2.
|
|||||||
## Features
|
## Features
|
||||||
|
|
||||||
- Check if a number is divisible by 2 via GET or POST requests
|
- Check if a number is divisible by 2 via GET or POST requests
|
||||||
|
- History endpoint to view all past checks
|
||||||
|
- Database integration with SQLAlchemy and SQLite
|
||||||
|
- Database migrations managed by Alembic
|
||||||
- Health endpoint for monitoring
|
- Health endpoint for monitoring
|
||||||
- OpenAPI documentation built-in
|
- OpenAPI documentation built-in
|
||||||
|
|
||||||
@ -48,6 +51,28 @@ Check if a number is divisible by 2 using a JSON request body.
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### GET /history
|
||||||
|
|
||||||
|
Get the history of all divisibility checks performed.
|
||||||
|
|
||||||
|
**Response:**
|
||||||
|
```json
|
||||||
|
[
|
||||||
|
{
|
||||||
|
"number": 42,
|
||||||
|
"is_divisible_by_2": true,
|
||||||
|
"id": 1,
|
||||||
|
"created_at": "2025-05-14T12:34:56.789Z"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"number": 7,
|
||||||
|
"is_divisible_by_2": false,
|
||||||
|
"id": 2,
|
||||||
|
"created_at": "2025-05-14T12:35:01.234Z"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
```
|
||||||
|
|
||||||
### GET /health
|
### GET /health
|
||||||
|
|
||||||
Health check endpoint to verify the API is running.
|
Health check endpoint to verify the API is running.
|
||||||
@ -68,6 +93,10 @@ Health check endpoint to verify the API is running.
|
|||||||
```
|
```
|
||||||
pip install -r requirements.txt
|
pip install -r requirements.txt
|
||||||
```
|
```
|
||||||
|
3. Run database migrations:
|
||||||
|
```
|
||||||
|
alembic upgrade head
|
||||||
|
```
|
||||||
|
|
||||||
## Running the API
|
## Running the API
|
||||||
|
|
||||||
|
101
alembic.ini
Normal file
101
alembic.ini
Normal file
@ -0,0 +1,101 @@
|
|||||||
|
# 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.
|
||||||
|
|
||||||
|
# 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
|
79
alembic/env.py
Normal file
79
alembic/env.py
Normal file
@ -0,0 +1,79 @@
|
|||||||
|
from logging.config import fileConfig
|
||||||
|
|
||||||
|
from sqlalchemy import engine_from_config
|
||||||
|
from sqlalchemy import pool
|
||||||
|
|
||||||
|
from alembic import context
|
||||||
|
from app.database.connection import Base
|
||||||
|
|
||||||
|
# Import models to register with SQLAlchemy metadata
|
||||||
|
# This import is needed even though it appears unused
|
||||||
|
import app.models.number # noqa: F401
|
||||||
|
|
||||||
|
# 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
|
||||||
|
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
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"}
|
39
alembic/versions/001_initial_migration.py
Normal file
39
alembic/versions/001_initial_migration.py
Normal file
@ -0,0 +1,39 @@
|
|||||||
|
"""Initial migration
|
||||||
|
|
||||||
|
Revision ID: 001
|
||||||
|
Revises:
|
||||||
|
Create Date: 2025-05-14
|
||||||
|
|
||||||
|
"""
|
||||||
|
|
||||||
|
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 number_checks table
|
||||||
|
op.create_table(
|
||||||
|
"number_checks",
|
||||||
|
sa.Column("id", sa.Integer(), nullable=False),
|
||||||
|
sa.Column("number", sa.Integer(), nullable=False),
|
||||||
|
sa.Column("is_divisible_by_2", sa.Boolean(), nullable=False),
|
||||||
|
sa.Column(
|
||||||
|
"created_at",
|
||||||
|
sa.DateTime(timezone=True),
|
||||||
|
server_default=sa.text("(CURRENT_TIMESTAMP)"),
|
||||||
|
),
|
||||||
|
sa.PrimaryKeyConstraint("id"),
|
||||||
|
)
|
||||||
|
op.create_index(op.f("ix_number_checks_id"), "number_checks", ["id"], unique=False)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
op.drop_index(op.f("ix_number_checks_id"), table_name="number_checks")
|
||||||
|
op.drop_table("number_checks")
|
1
app/__init__.py
Normal file
1
app/__init__.py
Normal file
@ -0,0 +1 @@
|
|||||||
|
# App package
|
0
app/api/__init__.py
Normal file
0
app/api/__init__.py
Normal file
88
app/api/endpoints.py
Normal file
88
app/api/endpoints.py
Normal file
@ -0,0 +1,88 @@
|
|||||||
|
from fastapi import APIRouter, Path as PathParam, Depends
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
from typing import List
|
||||||
|
|
||||||
|
from app.database.connection import get_db
|
||||||
|
from app.models.number import NumberCheck
|
||||||
|
from app.schemas.number import NumberRequest, DivisibilityResponse, NumberCheckResponse
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/", summary="API Root")
|
||||||
|
def read_root():
|
||||||
|
"""Welcome message for the API."""
|
||||||
|
return {"message": "Welcome to the Number Divisibility API"}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/divisibility/{number}",
|
||||||
|
response_model=DivisibilityResponse,
|
||||||
|
summary="Check divisibility (GET)",
|
||||||
|
)
|
||||||
|
def check_divisibility(
|
||||||
|
number: int = PathParam(..., description="The number to check divisibility for"),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Check if a number is divisible by 2.
|
||||||
|
|
||||||
|
Returns a JSON response with the number and a boolean indicating if it's divisible by 2.
|
||||||
|
"""
|
||||||
|
is_divisible = number % 2 == 0
|
||||||
|
|
||||||
|
# Log the check in the database
|
||||||
|
number_check = NumberCheck(number=number, is_divisible_by_2=is_divisible)
|
||||||
|
db.add(number_check)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(number_check)
|
||||||
|
|
||||||
|
return {"number": number, "is_divisible_by_2": is_divisible}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post(
|
||||||
|
"/divisibility",
|
||||||
|
response_model=DivisibilityResponse,
|
||||||
|
summary="Check divisibility (POST)",
|
||||||
|
)
|
||||||
|
def check_divisibility_post(request: NumberRequest, db: Session = Depends(get_db)):
|
||||||
|
"""
|
||||||
|
Check if a number is divisible by 2 using POST request.
|
||||||
|
|
||||||
|
Returns a JSON response with the number and a boolean indicating if it's divisible by 2.
|
||||||
|
"""
|
||||||
|
is_divisible = request.number % 2 == 0
|
||||||
|
|
||||||
|
# Log the check in the database
|
||||||
|
number_check = NumberCheck(number=request.number, is_divisible_by_2=is_divisible)
|
||||||
|
db.add(number_check)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(number_check)
|
||||||
|
|
||||||
|
return {"number": request.number, "is_divisible_by_2": is_divisible}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get(
|
||||||
|
"/history", response_model=List[NumberCheckResponse], summary="Check history"
|
||||||
|
)
|
||||||
|
def get_check_history(db: Session = Depends(get_db)):
|
||||||
|
"""
|
||||||
|
Get the history of number divisibility checks.
|
||||||
|
|
||||||
|
Returns a list of all number checks.
|
||||||
|
"""
|
||||||
|
return db.query(NumberCheck).all()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/health", summary="Health check")
|
||||||
|
def health_check():
|
||||||
|
"""
|
||||||
|
Health check endpoint to verify the API is running.
|
||||||
|
|
||||||
|
Returns a JSON response with status information.
|
||||||
|
"""
|
||||||
|
return {
|
||||||
|
"status": "healthy",
|
||||||
|
"api_version": "1.0.0",
|
||||||
|
"service": "Number Divisibility API",
|
||||||
|
}
|
3
app/database/__init__.py
Normal file
3
app/database/__init__.py
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
from app.database.connection import Base, engine, get_db
|
||||||
|
|
||||||
|
__all__ = ["Base", "engine", "get_db"]
|
27
app/database/connection.py
Normal file
27
app/database/connection.py
Normal file
@ -0,0 +1,27 @@
|
|||||||
|
from pathlib import Path
|
||||||
|
from sqlalchemy import create_engine
|
||||||
|
from sqlalchemy.ext.declarative import declarative_base
|
||||||
|
from sqlalchemy.orm import sessionmaker
|
||||||
|
|
||||||
|
# Create database 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)
|
||||||
|
|
||||||
|
Base = declarative_base()
|
||||||
|
|
||||||
|
|
||||||
|
# Dependency
|
||||||
|
def get_db():
|
||||||
|
db = SessionLocal()
|
||||||
|
try:
|
||||||
|
yield db
|
||||||
|
finally:
|
||||||
|
db.close()
|
3
app/models/__init__.py
Normal file
3
app/models/__init__.py
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
from app.models.number import NumberCheck
|
||||||
|
|
||||||
|
__all__ = ["NumberCheck"]
|
12
app/models/number.py
Normal file
12
app/models/number.py
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
from sqlalchemy import Column, Integer, Boolean, DateTime
|
||||||
|
from sqlalchemy.sql import func
|
||||||
|
from app.database.connection import Base
|
||||||
|
|
||||||
|
|
||||||
|
class NumberCheck(Base):
|
||||||
|
__tablename__ = "number_checks"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
number = Column(Integer, nullable=False)
|
||||||
|
is_divisible_by_2 = Column(Boolean, nullable=False)
|
||||||
|
created_at = Column(DateTime(timezone=True), server_default=func.now())
|
1
app/schemas/__init__.py
Normal file
1
app/schemas/__init__.py
Normal file
@ -0,0 +1 @@
|
|||||||
|
# Schema package
|
18
app/schemas/number.py
Normal file
18
app/schemas/number.py
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
from pydantic import BaseModel, ConfigDict
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
|
||||||
|
class NumberRequest(BaseModel):
|
||||||
|
number: int
|
||||||
|
|
||||||
|
|
||||||
|
class DivisibilityResponse(BaseModel):
|
||||||
|
number: int
|
||||||
|
is_divisible_by_2: bool
|
||||||
|
|
||||||
|
|
||||||
|
class NumberCheckResponse(DivisibilityResponse):
|
||||||
|
id: int
|
||||||
|
created_at: datetime
|
||||||
|
|
||||||
|
model_config = ConfigDict(from_attributes=True)
|
62
main.py
62
main.py
@ -1,58 +1,18 @@
|
|||||||
from fastapi import FastAPI, HTTPException, Path as PathParam
|
from fastapi import FastAPI
|
||||||
from pydantic import BaseModel
|
from app.api.endpoints import router
|
||||||
from pathlib import Path
|
from app.database.connection import Base, engine
|
||||||
|
|
||||||
|
# Create the database tables
|
||||||
|
Base.metadata.create_all(bind=engine)
|
||||||
|
|
||||||
# Create the FastAPI app
|
# Create the FastAPI app
|
||||||
app = FastAPI(
|
app = FastAPI(
|
||||||
title="Number Divisibility API",
|
title="Number Divisibility API",
|
||||||
description="A simple API to check if a number is divisible by 2",
|
description="A simple API to check if a number is divisible by 2",
|
||||||
version="1.0.0"
|
version="1.0.0",
|
||||||
|
docs_url="/docs",
|
||||||
|
redoc_url="/redoc",
|
||||||
)
|
)
|
||||||
|
|
||||||
class NumberRequest(BaseModel):
|
# Include the router
|
||||||
number: int
|
app.include_router(router)
|
||||||
|
|
||||||
class DivisibilityResponse(BaseModel):
|
|
||||||
number: int
|
|
||||||
is_divisible_by_2: bool
|
|
||||||
|
|
||||||
@app.get("/")
|
|
||||||
def read_root():
|
|
||||||
return {"message": "Welcome to the Number Divisibility API"}
|
|
||||||
|
|
||||||
@app.get("/divisibility/{number}", response_model=DivisibilityResponse)
|
|
||||||
def check_divisibility(number: int = PathParam(..., description="The number to check divisibility for")):
|
|
||||||
"""
|
|
||||||
Check if a number is divisible by 2.
|
|
||||||
|
|
||||||
Returns a JSON response with the number and a boolean indicating if it's divisible by 2.
|
|
||||||
"""
|
|
||||||
return {
|
|
||||||
"number": number,
|
|
||||||
"is_divisible_by_2": number % 2 == 0
|
|
||||||
}
|
|
||||||
|
|
||||||
@app.post("/divisibility", response_model=DivisibilityResponse)
|
|
||||||
def check_divisibility_post(request: NumberRequest):
|
|
||||||
"""
|
|
||||||
Check if a number is divisible by 2 using POST request.
|
|
||||||
|
|
||||||
Returns a JSON response with the number and a boolean indicating if it's divisible by 2.
|
|
||||||
"""
|
|
||||||
return {
|
|
||||||
"number": request.number,
|
|
||||||
"is_divisible_by_2": request.number % 2 == 0
|
|
||||||
}
|
|
||||||
|
|
||||||
@app.get("/health")
|
|
||||||
def health_check():
|
|
||||||
"""
|
|
||||||
Health check endpoint to verify the API is running.
|
|
||||||
|
|
||||||
Returns a JSON response with status information.
|
|
||||||
"""
|
|
||||||
return {
|
|
||||||
"status": "healthy",
|
|
||||||
"api_version": app.version,
|
|
||||||
"service": "Number Divisibility API"
|
|
||||||
}
|
|
||||||
|
@ -1,3 +1,6 @@
|
|||||||
fastapi==0.104.1
|
fastapi==0.104.1
|
||||||
uvicorn==0.23.2
|
uvicorn==0.23.2
|
||||||
pydantic==2.4.2
|
pydantic==2.4.2
|
||||||
|
sqlalchemy==2.0.23
|
||||||
|
alembic==1.12.1
|
||||||
|
ruff==0.1.5
|
Loading…
x
Reference in New Issue
Block a user