
HTTP API vs WebSocket API:選擇哪個來實現實時通信?
首先,需要在 OpenM 服務器上創建賬戶并獲取令牌。令牌用于 API 的身份驗證。
{
""username"": ""your_username"",
""password"": ""your_password""
}
可以使用以下代碼向 API 的認證端點發送這個 JSON 格式的數據,從而獲取令牌。
import requests
import json
url = ""https://api.example.com/auth""
data = {
""username"": ""your_username"",
""password"": ""your_password""
}
response = requests.post(url, json=data)
token = response.json().get(""token"")
獲取令牌后,使用它來獲取用戶列表。將令牌添加到請求頭中,并發送 GET 請求。
headers = {
""Authorization"": f""Bearer {token}"",
""Content-Type"": ""application/json""
}
response = requests.get(""https://api.example.com/users"", headers=headers)
users = response.json()
print(users)
同樣地,可以使用以下代碼獲取項目列表。
response = requests.get(""https://api.example.com/projects"", headers=headers)
projects = response.json()
print(projects)
雖然 SOAP API 常用 XML 格式,但 REST API 通常使用 JSON 格式。如果需要從 XML 轉換為 JSON,可以按照以下方法進行。
<request>
<username>your_username</username>
<password>your_password</password>
</request>
將上述 XML 數據轉換為 JSON 格式。
{
""username"": ""your_username"",
""password"": ""your_password""
}
在 REST API 中,通過 HTTP 方法(GET、POST、PUT、DELETE)操作資源。例如,要獲取用戶列表,使用 GET 方法;要創建新用戶,使用 POST 方法。
# 創建新用戶
new_user = {
""username"": ""new_user"",
""password"": ""new_password""
}
response = requests.post(""https://api.example.com/users"", headers=headers, json=new_user)
print(response.json())
Authorization: Bearer {token}
的形式添加到頭部。Content-Type: application/json
。response.json()
獲取數據。從 SOAP API 轉換到 REST API 主要關注 HTTP 方法的使用和數據格式的變更。REST API 使用 JSON 格式發送和接收數據,并通過 HTTP 方法(GET、POST、PUT、DELETE)操作資源。通過獲取令牌并將其添加到頭部,可以進行身份驗證和數據獲取。
原文引自YouTube視頻:https://www.youtube.com/watch?v=I5gvHmSzfok