簡體   English   中英

使用python的API請求

[英]API requests using python

我正在嘗試使用python發出請求。 該API使用:

curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' -d '{ \ 
   "$class": "org.acme.model.sensor", \ 
   "sensorId": "1", \ 
   "type": "Temperature", \ 
   "value": "10", \ 
   "timestamp": 1234123 \ 
 }' 'http://localhost:3000/api/sensor'

創建一個新的傳感器。 我正在嘗試使用python進行操作,並創建了概念證明:

data = {
    "$class": "org.acme.model.sensor",
    "sensorId": "",  #change in the loop with i
    "type": "Temperature",
    "value": "10",
    "timestamp": 382453824
}

header = {
    "Content-Type" : "application/json",
    "Accept":"application/json"
}

url = "http://localhost:3000/api/sensor"
for i in range(2):
    data["sensorId"]=str(i+1)
    response = requests.post(url, data=data, headers=header)

    #Now I modify the data
    data["Temperature"]="50"
    response = requests.put(url, data=data, headers=header)

現在,要擦除:

for i in range(2):
    url="http://localhost:3000/api/sensor/"+str(i+1)
    response = requests.delete(url)

使用curl,它可以正常工作,但不能使用python代碼。 它甚至無法創建對象。

import requests
import json

header = {
"Content-Type" : "application/json",
"Accept":"application/json"
}

您需要使用json.dumps將字典轉換為正確的格式,並且需要使用request.post而不是delete

request_url = 'YOUR_END_POINT'
data = json.dumps(data)
response = requests.post(url=request_url,data=data,headers=headers)

我認為應該解決。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM