|
|
import os |
|
|
import httpx |
|
|
from fastapi import FastAPI, HTTPException |
|
|
from fastapi.middleware.cors import CORSMiddleware |
|
|
from pydantic import BaseModel |
|
|
|
|
|
app = FastAPI( |
|
|
title="SAP Purchase Order API Demo", |
|
|
description=( |
|
|
"Fetches purchase order data from SAP Sandbox API.\n\n" |
|
|
"Designed for integration with OpenAI Agentkit UI — " |
|
|
"Agentkit auto-discovers endpoints from `/openapi.json`." |
|
|
), |
|
|
version="1.0.0", |
|
|
) |
|
|
|
|
|
|
|
|
app.add_middleware( |
|
|
CORSMiddleware, |
|
|
allow_origins=["*"], |
|
|
allow_credentials=True, |
|
|
allow_methods=["*"], |
|
|
allow_headers=["*"], |
|
|
) |
|
|
|
|
|
|
|
|
SAP_API_KEY = os.getenv("SAP_API_KEY") |
|
|
SAP_BASE_URL = ( |
|
|
"https://sandbox.api.sap.com/s4hanacloud/sap/opu/odata4/" |
|
|
"sap/api_purchaseorder_2/srvd_a2x/sap/purchaseorder/0001/PurchaseOrder?$top=50" |
|
|
) |
|
|
|
|
|
|
|
|
|
|
|
class PurchaseOrderItem(BaseModel): |
|
|
PurchaseOrder: str | None = None |
|
|
Supplier: str | None = None |
|
|
CreatedByUser: str | None = None |
|
|
CreatedDateTime: str | None = None |
|
|
|
|
|
|
|
|
class PurchaseOrderResponse(BaseModel): |
|
|
source: str |
|
|
count: int |
|
|
data: list[PurchaseOrderItem] | dict |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@app.get("/health", summary="Health check", tags=["System"]) |
|
|
async def health_check(): |
|
|
"""Simple endpoint to verify the backend is running.""" |
|
|
return {"status": "ok", "message": "SAP Purchase Order API backend is running"} |
|
|
|
|
|
|
|
|
@app.get( |
|
|
"/purchase-orders", |
|
|
response_model=PurchaseOrderResponse, |
|
|
summary="Get Purchase Orders", |
|
|
tags=["Purchase Orders"], |
|
|
description="Fetch top 50 purchase orders from SAP Sandbox API.", |
|
|
) |
|
|
async def get_purchase_orders(): |
|
|
"""Fetches purchase orders from SAP Sandbox API""" |
|
|
if not SAP_API_KEY: |
|
|
raise HTTPException(status_code=500, detail="SAP_API_KEY not found in environment") |
|
|
|
|
|
headers = {"APIKey": SAP_API_KEY} |
|
|
|
|
|
try: |
|
|
async with httpx.AsyncClient(timeout=30.0) as client: |
|
|
resp = await client.get(SAP_BASE_URL, headers=headers) |
|
|
resp.raise_for_status() |
|
|
data = resp.json() |
|
|
po_items = data.get("value", []) |
|
|
return {"source": "SAP Sandbox", "count": len(po_items), "data": po_items} |
|
|
except httpx.HTTPStatusError as e: |
|
|
raise HTTPException(status_code=e.response.status_code, detail=f"SAP API error: {e.response.text}") |
|
|
except Exception as e: |
|
|
raise HTTPException(status_code=500, detail=str(e)) |
|
|
|