89 lines
2.4 KiB
Python
89 lines
2.4 KiB
Python
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",
|
|
}
|