Python API的麻烦

时间:2018-04-10 15:16:29

标签: python api

我的任务是当场学习Python,觉得我已经溺水了。我试图翻译同事提供的内容,但我真的很挣扎。我正在尝试使用的API位于:https://dev.skuvault.com/v1.0/reference#getonlinesalestatus 我的代码是:

import requests, json

# Skuvault URIs and Token
SkuBase = "https://app.skuvault.com/api/sales/getOnlineSaleStatus"
SkuProductsUri = SkuBase + "Products(id)/Attributes('name')"
SkuAuthToken = ""

print "[+] Requesting: " + SkuProductsUri

response = requests.post(SkuProductsUri, headers={'Authorization': 'Bearer ' + SkuAuthToken})
productsJson = json.loads(response.status_code)

print "[*] Status: %d\n[*] Reason: %s\n[*] Message: %s\n[*] Raw: %s\n\n" \
    % (response.status_code, response.reason, productsJson['Message'], response.text[:300])

尝试运行脚本时收到以下错误

  

[+]申请:https://app.skuvault.com/api/sales/getOnlineSaleStatusProducts(id)/Attributes('姓名')   Traceback(最近一次调用最后一次):     文件“test-api.py”,第11行,in       productsJson = json.loads(response.status_code)     文件“/usr/local/Cellar/python@2/2.7.14_3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/init.py”,第339行,在负载       return _default_decoder.decode(s)     文件“/usr/local/Cellar/python@2/2.7.14_3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py”,第364行,解码       obj,end = self.raw_decode(s,idx = _w(s,0).end())   TypeError:期望的字符串或缓冲区

就像我说的那样,在此之前我从未使用过Python,感觉有点不知所措。感谢。

1 个答案:

答案 0 :(得分:1)

您没有正确调用API。请注意,API期望您POST一个请求,并且它期望请求有效负载看起来像

{
  "OrderIds": [
    "my-id"
  ],
  "TenantToken": "my-tenant-token",
  "UserToken": "my-user-token"
}

如果我做的很相似,我可能会这样做:

sku_base = "https://app.skuvault.com/api/sales/getOnlineSaleStatus"
response = requests.post(
    sku_base, 
    json={
      "OrderIds": [ "my-order-id" ], 
      "TenantToken": "my-tenant-token", 
      "UserToken": "my-user-token"
    }
)

# NOTE: you are not using the status code here. That's an int and will error.
productsJson = json.loads(response.text)
# This is also valid and will result in the same object:
productsJson = response.json()

print "[*] Status: %d\n[*] Reason: %s\n[*] Message: %s\n[*] Raw: %s\n\n" \
% (response.status_code, response.reason, productsJson['Message'], response.text[:300])

旁注:

不再维护Python 2。建议您专门使用Python 3。