創建 API
創建 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 請求(GETPOSTPUTDELETE)。數據是一個包含項目數組的對象,每個項目都有一個 ID、名稱和價格。

當調用該函數時,它首先從事件對象中確定請求的 HTTP 方法。然后它相應地處理請求:

通過單擊“操作”并選擇“部署 API”來部署 API。

Postman 測試

選擇部署階段(例如“prod”或“test”)并點擊“Deploy”。使用生成的 API 端點向您的 API 發出請求。

Postman 測試

在 Postman 中運行和測試代碼

現在,我們的 API 已啟動并運行。您可以通過 Postman 發送測試 HTTP 請求。通過向您的 發送請求invoke URL,您應該會看到200 OK狀態代碼。對于此測試,傳入請求不需要請求正文。

Postman 測試

總結

這樣,我們就使用 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/

上一篇:

如何快速實現REST API集成以優化業務流程

下一篇:

使用NestJS和Prisma構建REST API:輸入驗證和轉換
#你可能也喜歡這些API文章!

我們有何不同?

API服務商零注冊

多API并行試用

數據驅動選型,提升決策效率

查看全部API→
??

熱門場景實測,選對API

#AI文本生成大模型API

對比大模型API的內容創意新穎性、情感共鳴力、商業轉化潛力

25個渠道
一鍵對比試用API 限時免費

#AI深度推理大模型API

對比大模型API的邏輯推理準確性、分析深度、可視化建議合理性

10個渠道
一鍵對比試用API 限時免費