使用x-api-key从cm commerce中提取数据

xzabzqsa  于 2021-09-08  发布在  Java
关注(0)|答案(1)|浏览(393)

我试图通过参考本指南来获取数据。我是新来的。我可以用api键和url提取数据吗。因为我只有api密钥和url。我没有任何其他参数。以下是我尝试的方法:

import urllib.parse
import urllib.request

url = "https://commerce.campaignmonitor.com/api/v1/abandoned-carts/campaigns"
header={"x-api-key" : 'my_api_key'}
post_param = urllib.parse.urlencode({
                    'user' : 'i_dont_know',
           'status-update' : 'i_dont_know'
          }).encode('UTF-8')

req = urllib.request.Request(url, post_param, header)
response = urllib.request.urlopen(req)

这是:

from requests.auth import HTTPBasicAuth
import requests
import urllib

url ="https://commerce.campaignmonitor.com/api/v1/abandoned-carts/campaigns"
headers = {"Accept": "application/json"}
auth = HTTPBasicAuth('my_api_key', 'i_dont_know')

req = requests.get(url, headers=headers , auth=auth)
response = urllib.request.urlopen(req)

但我有一个错误:

AttributeError: 'Response' object has no attribute 'type'

在其他方法中,我得到401错误

4szc88ey

4szc88ey1#

python-requests 独自一人可以为你做到这一点(不需要 urllib ). 你有 API key 所以你不应该使用 HTTPBasicAuth 这应该适合您:

import requests

url ="https://commerce.campaignmonitor.com/api/v1/abandoned-carts/campaigns"

# like the doc says, provide API key in header

headers = {"Accept": "application/json",
'X-ApiKey': 'my_api_key'}

req = requests.get(url, headers=headers)
print(req.json())

相关问题