向API发送请求时出现TypeError和urllib.error.HTTPError

时间:2019-04-12 04:42:53

标签: python api

我正在尝试从Python向FullContact API发送请求。我只是在他们的documentation中尝试了基本代码。这给了TypeError: POST data should be bytes, an iterable of bytes, or a file object. It cannot be of type str.,然后我尝试像在TypeError: POST data should be bytes or an iterable of bytes. It cannot be str中一样编码字符串。但是,这给了我urllib.error.HTTPError: HTTP Error 400: Bad Request。检查here以获得有关其错误代码的详细信息。我正在他们的documentation中使用代码。我哪里错了?

  

未编码的代码

import urllib.request, json

req = urllib.request.Request('https://api.fullcontact.com/v3/person.enrich')
req.add_header('Authorization', 'Bearer {api key}')
data = json.dumps({
    "email": "bart@fullcontact.com",
    "webhookUrl": "http://www.fullcontact.com/hook"
})
response = urllib.request.urlopen(req,data)

TypeError: POST data should be bytes, an iterable of bytes, or a file object. It cannot be of type str

  

带有编码的代码

import urllib.request, json

req = urllib.request.Request('https://api.fullcontact.com/v3/person.enrich')
req.add_header('Authorization', 'Bearer {api key}')
data = json.dumps({
    "email": "bart@fullcontact.com",
    "webhookUrl": "http://www.fullcontact.com/hook"
})
data_encoded = data.encode('utf-8')
response = urllib.request.urlopen(req,data_encoded)

urllib.error.HTTPError: HTTP Error 400: Bad Request

0 个答案:

没有答案