我正在尝试在rest api上发布请求结构。
我的代码:
def pack_orders(self, orderItemId, invoiceDate, invoiceNumber, tax, serialNumbers=None, subOrderItemId = None, subSerialNumbers = None, subInvoiceDate = None, subTax = None):
url = "https://api.flipkart.net/sellers/orders/labels"
payload = {[{"orderItemId": orderItemId,
"serialNumbers": serialNumbers,
"invoiceDate": invoiceDate,
"invoiceNumber": invoiceNumber,
"tax": tax,
"subItems": [{
"orderItemId": subOrderItemId,
"serialNumbers": subSerialNumbers,
"invoiceDate": subInvoiceDate,
"tax": subTax}]
}],}
return self.session.post(url, params=payload)
调用上述函数:
label = fk.pack_orders(orderItemId='232519872', invoiceDate='2015-08-13', invoiceNumber='INVSTR01', tax=5)
print label.status_code
print label.url
print label.content
它抛出错误422.我知道它必须对请求参数结构做一些事情。我无法确定错误来源。
以下是任何帮助文档的链接。 Documentation
答案 0 :(得分:4)
API期待JSON
格式的数据
python requests 也很简单易用。
import requests
data = {[{"orderItemId": orderItemId,
"serialNumbers": serialNumbers,
"invoiceDate": invoiceDate,
"invoiceNumber": invoiceNumber,
"tax": tax,
"subItems": [{
"orderItemId": subOrderItemId,
"serialNumbers": subSerialNumbers,
"invoiceDate": subInvoiceDate,
"tax": subTax}]
}],}
r = requests.post(url, json=data)
r.status_code
r.json()
示例请求(使用shell):
成功提出请求。获得401无效身份验证(显而易见的原因)
In [19]: import requests
In [20]: url = "https://api.flipkart.net/sellers/orders/labels"
In [21]: data = [{
....: "orderItemId": 1179576,
....: "serialNumbers": ["IMEI1-UNIT1"],
....: "invoiceDate": "2014-08-29",
....: "invoiceNumber": "INV-01",
....: "tax": 100.98,
....: "subItems": [{
....: "orderItemId": 1173467,
....: "serialNumbers": [ ],
....: "invoiceDate": "2014-08-29",
....: "tax": 10.98
....: }]
....: }]
In [22]: r = requests.post(url, json=data)
In [23]: r.status_code
Out[23]: 401
In [24]: r.json()
Out[24]:
{u'error': u'unauthorized',
u'error_description': u'An Authentication object was not found in the SecurityContext'}
答案 1 :(得分:0)
你应该尝试:
return self.session.post(url, data=payload)
而不是
return self.session.post(url, params=payload)