
如何快速實現REST API集成以優化業務流程
import json
# Example data
data = {
"items": [
{"id": 1, "name": "Item 1", "price": 10.99},
{"id": 2, "name": "Item 2", "price": 15.99},
{"id": 3, "name": "Item 3", "price": 20.99},
]
}
def lambda_handler(event, context):
# Determine the HTTP method of the request
http_method = event["httpMethod"]
# Handle GET request
if http_method == "GET":
# Return the data in the response
response = {
"statusCode": 200,
"body": json.dumps(data)
}
return response
# Handle POST request
elif http_method == "POST":
# Retrieve the request's body and parse it as JSON
body = json.loads(event["body"])
# Add the received data to the example data
data["items"].append(body)
# Return the updated data in the response
response = {
"statusCode": 200,
"body": json.dumps(data)
}
return response
# Handle PUT request
elif http_method == "PUT":
# Retrieve the request's body and parse it as JSON
body = json.loads(event["body"])
# Update the example data with the received data
for item in data["items"]:
if item["id"] == body["id"]:
item.update(body)
break
# Return the updated data in the response
response = {
"statusCode": 200,
"body": json.dumps(data)
}
return response
# Handle DELETE request
elif http_method == "DELETE":
# Retrieve the request's body and parse it as JSON
body = json.loads(event["body"])
# Find the item with the specified id in the example data
for i, item in enumerate(data["items"]):
if item["id"] == body["id"]:
# Remove the item from the example data
del data["items"][i]
break
# Return the updated data in the response
response = {
"statusCode": 200,
"body": json.dumps(data)
}
return response
else:
# Return an error message for unsupported methods
response = {
"statusCode": 405,
"body": json.dumps({"error": "Method not allowed"})
}
return response
此代碼定義了一個 Lambda 函數,lambda_handler
用于處理針對某些數據的不同類型的 HTTP 請求(GET
、POST
、PUT
、DELETE
)。數據是一個包含項目數組的對象,每個項目都有一個 ID、名稱和價格。
當調用該函數時,它首先從事件對象中確定請求的 HTTP 方法。然后它相應地處理請求:
通過單擊“操作”并選擇“部署 API”來部署 API。
選擇部署階段(例如“prod”或“test”)并點擊“Deploy”。使用生成的 API 端點向您的 API 發出請求。
現在,我們的 API 已啟動并運行。您可以通過 Postman 發送測試 HTTP 請求。通過向您的 發送請求invoke URL
,您應該會看到200 OK
狀態代碼。對于此測試,傳入請求不需要請求正文。
這樣,我們就使用 AWS Lambda 和 Python 創建了一個簡單的 RESTful API。此代碼可以作為為您的應用程序創建更復雜 API 的基礎。在繼續開發 API 時,您可能需要考慮實施安全措施,例如 API 密鑰、與 API 網關集成,監控 API 的使用情況或通過以下方式創造收入API 貨幣化。
原文地址:https://www.moesif.com/blog/technical/api-development/Building-Rest-API-With-AWS-Gateway-And-Python/