FastAPI إطار عمل حديث وسريع لبناء REST APIs مع Python.
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import irisnative
app = FastAPI(title="IRIS Academy API", version="1.0")
class Employee(BaseModel):
name: str
department: str
salary: float
def get_db():
return irisnative.createConnection(
'localhost', 52773, 'USER', '_SYSTEM', 'SYS'
)
@app.get("/employees")
def list_employees(dept: str = None, limit: int = 100):
conn = get_db()
query = "SELECT ID, Name, Department, Salary FROM Employee"
if dept:
query += f" WHERE Department = '{dept}'"
query += f" LIMIT {limit}"
cursor = conn.cursor()
cursor.execute(query)
return [
{"id": r[0], "name": r[1], "dept": r[2], "salary": r[3]}
for r in cursor
]
@app.post("/employees", status_code=201)
def create_employee(emp: Employee):
conn = get_db()
cursor = conn.cursor()
cursor.execute(
"INSERT INTO Employee (Name, Department, Salary) VALUES (?, ?, ?)",
[emp.name, emp.department, emp.salary]
)
conn.commit()
return {"status": "created", "name": emp.name}
@app.get("/employees/{emp_id}")
def get_employee(emp_id: int):
conn = get_db()
cursor = conn.cursor()
cursor.execute("SELECT ID, Name, Department, Salary FROM Employee WHERE ID = ?", [emp_id])
row = cursor.fetchone()
if not row:
raise HTTPException(status_code=404, detail="Employee not found")
return {"id": row[0], "name": row[1], "dept": row[2], "salary": row[3]}