[英]Python json POST request status 200 while expecting status 201
I'm trying to do a POST request to a web server in an attempt to create a new resource. 我正在尝试向Web服务器发出POST请求,以尝试创建新资源。 I'm fairly new to both Python and the platform I'm trying to communicate with on the server, so I'm not sure if it's my python skills require a bit more practice or if I'm just not submitting a request correctly to the server.
我对要在服务器上进行通信的Python和平台都不太熟悉,所以我不确定这是否是我的python技能需要更多的练习,或者我是否只是未正确提交请求到服务器。 Here's my code:
这是我的代码:
import requests
apiKey = "[APIKEY]"
serverUrl = "http://192.168.0.5/api/v1.0/payments"
values = """
{
"clientId": 1,
"method": 3,
"createdDate": "2016-09-12T00:00:00+0000",
"amount": 10,
"note": "",
"invoiceIds": []
}
"""
headers = {
'X-Auth-App-Key': apiKey,
'Content-Type': 'application/json'
}
r = requests.post(serverUrl, data=values, headers=headers)
r
The server responds with a Response 200 (OK) message, but since I'm trying to create a new resource it should respond with a Response 201 (Created) message. 服务器以响应200(确定)消息进行响应,但是由于我尝试创建新资源,因此服务器应以响应201(已创建)消息进行响应。 Any ideas what I'm doing wrong?
有什么想法我做错了吗?
Try using https://
, 尝试使用
https://
,
change serverUrl = "http://192.168.0.5/api/v1.0/payments"
更改
serverUrl = "http://192.168.0.5/api/v1.0/payments"
to 至
serverUrl = "https://192.168.0.5/api/v1.0/payments"
This probably won't result in a different HTTP status code, but you can send JSON encoded dictionaries directly by using the json
parameter to requests.post()
. 这可能不会导致不同的HTTP状态代码,但是您可以使用
json
参数直接将JSON编码的字典发送给request.post requests.post()
。 So values
can be a dictionary, and requests
will set the content type so you don't need to in headers
: 因此,
values
可以是字典, requests
将设置内容类型,因此您无需在headers
:
values =
{
"clientId": 1,
"method": 3,
"createdDate": "2016-09-12T00:00:00+0000",
"amount": 123.45,
"note": "",
"invoiceIds": []
}
headers = {'X-Auth-App-Key': apiKey}
r = requests.post(serverUrl, json=values, headers=headers)
It's just a little cleaner. 只是有点清洁。
Regarding the expected 201 response, is the resource actually created? 关于预期的201响应,是否实际创建了资源? Do you get a 201 response when using other tools such as
curl
? 使用其他工具(例如
curl
时,您是否收到201响应?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.