یک API ساده برای ماشین حساب با استفاده از FastAPI طراحی میکنم:
python
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import Union
import math
app = FastAPI(title="Calculator API", description="یک API ساده برای عملیات ریاضی")
# مدلهای داده
class BasicOperation(BaseModel):
a: float
b: float
class SingleNumber(BaseModel):
number: float
class PowerOperation(BaseModel):
base: float
exponent: float
# عملیات پایه
@app.post("/add")
async def add(operation: BasicOperation):
"""جمع دو عدد"""
result = operation.a + operation.b
return {"result": result, "operation": f"{operation.a} + {operation.b} = {result}"}
@app.post("/subtract")
async def subtract(operation: BasicOperation):
"""تفریق دو عدد"""
result = operation.a - operation.b
return {"result": result, "operation": f"{operation.a} - {operation.b} = {result}"}
@app.post("/multiply")
async def multiply(operation: BasicOperation):
"""ضرب دو عدد"""
result = operation.a * operation.b
return {"result": result, "operation": f"{operation.a} × {operation.b} = {result}"}
@app.post("/divide")
async def divide(operation: BasicOperation):
"""تقسیم دو عدد"""
if operation.b == 0:
raise HTTPException(status_code=400, detail="تقسیم بر صفر امکانپذیر نیست")
result = operation.a / operation.b
return {"result": result, "operation": f"{operation.a} ÷ {operation.b} = {result}"}
# عملیات پیشرفته
@app.post("/power")
async def power(operation: PowerOperation):
"""توان رسانی"""
result = operation.base ** operation.exponent
return {"result": result, "operation": f"{operation.base}^{operation.exponent} = {result}"}
@app.post("/square-root")
async def square_root(number: SingleNumber):
"""جذر دوم"""
if number.number < 0:
raise HTTPException(status_code=400, detail="جذر اعداد منفی تعریف نشده است")
result = math.sqrt(number.number)
return {"result": result, "operation": f"√{number.number} = {result}"}
@app.post("/factorial")
async def factorial(number: SingleNumber):
"""فاکتوریل"""
if number.number < 0 or number.number != int(number.number):
raise HTTPException(status_code=400, detail="فاکتوریل فقط برای اعداد صحیح غیرمنفی تعریف شده است")
result = math.factorial(int(number.number))
return {"result": result, "operation": f"{int(number.number)}! = {result}"}
# عملیات مثلثاتی (بر حسب رادیان)
@app.post("/sin")
async def sine(number: SingleNumber):
"""سینوس"""
result = math.sin(number.number)
return {"result": result, "operation": f"sin({number.number}) = {result}"}
@app.post("/cos")
async def cosine(number: SingleNumber):
"""کسینوس"""
result = math.cos(number.number)
return {"result": result, "operation": f"cos({number.number}) = {result}"}
@app.post("/tan")
async def tangent(number: SingleNumber):
"""تانژانت"""
result = math.tan(number.number)
return {"result": result, "operation": f"tan({number.number}) = {result}"}
# لگاریتم
@app.post("/log")
async def logarithm(number: SingleNumber):
"""لگاریتم طبیعی"""
if number.number <= 0:
raise HTTPException(status_code=400, detail="لگاریتم فقط برای اعداد مثبت تعریف شده است")
result = math.log(number.number)
return {"result": result, "operation": f"ln({number.number}) = {result}"}
@app.post("/log10")
async def log10(number: SingleNumber):
"""لگاریتم مبنای ۱۰"""
if number.number <= 0:
raise HTTPException(status_code=400, detail="لگاریتم فقط برای اعداد مثبت تعریف شده است")
result = math.log10(number.number)
return {"result": result, "operation": f"log₁₀({number.number}) = {result}"}
# صفحه اصلی
@app.get("/")
async def root():
return {"message": "به API ماشین حساب خوش آمدید! برای مشاهده مستندات به /docs مراجعه کنید."}
# اجرا
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
برای اجرای این API ابتدا کتابخانههای مورد نیاز را نصب کنید:
bash
pip install fastapi uvicorn
سپس فایل را با نام calculator_api.py ذخیره کرده و اجرا کنید:
bash
python calculator_api.py
یا با uvicorn:
bash
uvicorn calculator_api:app --reload
API در آدرس http://localhost:8000 در دسترس خواهد بود و میتوانید مستندات تعاملی آن را در http://localhost:8000/docs مشاهده کنید.
مثال استفاده با curl:
bash
# جمع دو عدد
curl -X POST "http://localhost:8000/add" -H "Content-Type: application/json" -d '{"a": 5, "b": 3}'
# تقسیم دو عدد
curl -X POST "http://localhost:8000/divide" -H "Content-Type: application/json" -d '{"a": 10, "b": 2}'
# جذر دوم
curl -X POST "http://localhost:8000/square-root" -H "Content-Type: application/json" -d '{"number": 16}'
این API شامل عملیات پایه ریاضی، عملیات پیشرفته، و توابع مثلثاتی است و خطاهای مناسب را برای ورودیهای نامعتبر برمیگرداند.