PD03 commited on
Commit
2f9831b
·
verified ·
1 Parent(s): 98e4842

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +80 -0
app.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import httpx
3
+ from fastapi import FastAPI, HTTPException
4
+ from fastapi.middleware.cors import CORSMiddleware
5
+ from pydantic import BaseModel
6
+
7
+ app = FastAPI(
8
+ title="SAP Purchase Order API Demo",
9
+ description=(
10
+ "Fetches purchase order data from SAP Sandbox API.\n\n"
11
+ "Designed for integration with OpenAI Agentkit UI — "
12
+ "Agentkit auto-discovers endpoints from `/openapi.json`."
13
+ ),
14
+ version="1.0.0",
15
+ )
16
+
17
+ # Allow all origins for Agentkit / external calls
18
+ app.add_middleware(
19
+ CORSMiddleware,
20
+ allow_origins=["*"],
21
+ allow_credentials=True,
22
+ allow_methods=["*"],
23
+ allow_headers=["*"],
24
+ )
25
+
26
+ # Read secret from Hugging Face environment
27
+ SAP_API_KEY = os.getenv("SAP_API_KEY")
28
+ SAP_BASE_URL = (
29
+ "https://sandbox.api.sap.com/s4hanacloud/sap/opu/odata4/"
30
+ "sap/api_purchaseorder_2/srvd_a2x/sap/purchaseorder/0001/PurchaseOrder?$top=50"
31
+ )
32
+
33
+ # --- Models ---
34
+
35
+ class PurchaseOrderItem(BaseModel):
36
+ PurchaseOrder: str | None = None
37
+ Supplier: str | None = None
38
+ CreatedByUser: str | None = None
39
+ CreatedDateTime: str | None = None
40
+
41
+
42
+ class PurchaseOrderResponse(BaseModel):
43
+ source: str
44
+ count: int
45
+ data: list[PurchaseOrderItem] | dict
46
+
47
+
48
+ # --- Routes ---
49
+
50
+ @app.get("/health", summary="Health check", tags=["System"])
51
+ async def health_check():
52
+ """Simple endpoint to verify the backend is running."""
53
+ return {"status": "ok", "message": "SAP Purchase Order API backend is running"}
54
+
55
+
56
+ @app.get(
57
+ "/purchase-orders",
58
+ response_model=PurchaseOrderResponse,
59
+ summary="Get Purchase Orders",
60
+ tags=["Purchase Orders"],
61
+ description="Fetch top 50 purchase orders from SAP Sandbox API.",
62
+ )
63
+ async def get_purchase_orders():
64
+ """Fetches purchase orders from SAP Sandbox API"""
65
+ if not SAP_API_KEY:
66
+ raise HTTPException(status_code=500, detail="SAP_API_KEY not found in environment")
67
+
68
+ headers = {"APIKey": SAP_API_KEY}
69
+
70
+ try:
71
+ async with httpx.AsyncClient(timeout=30.0) as client:
72
+ resp = await client.get(SAP_BASE_URL, headers=headers)
73
+ resp.raise_for_status()
74
+ data = resp.json()
75
+ po_items = data.get("value", [])
76
+ return {"source": "SAP Sandbox", "count": len(po_items), "data": po_items}
77
+ except httpx.HTTPStatusError as e:
78
+ raise HTTPException(status_code=e.response.status_code, detail=f"SAP API error: {e.response.text}")
79
+ except Exception as e:
80
+ raise HTTPException(status_code=500, detail=str(e))