首页 > 解决方案 > 试图从 API 获取 json 数据,得到 TypeError

问题描述

TypeError: POST 数据应该是字节、可迭代的字节或文件对象。它不能是 str 类型。

import json
import urllib.request as req
from urllib.parse import urlencode

url = "https://apiurl.example/search/"

payload = {"SearchString":"mysearch"}

response = req.urlopen(url, urlencode(payload))
data = response.read()

print(data.decode("utf-8"))

我究竟做错了什么?我在 API 的在线界面中尝试过的 url 或“有效负载”没有任何问题。在添加 urlencode 和 utf-8 解码之前,我收到一条错误消息:“TypeError: can't concat str to bytes”。在某些时候它返回了一个空列表,但不记得我当时做了什么。无论如何,它应该返回一些如上所述的数据。谢谢你的时间。

标签: pythonjsonapi

解决方案


我从来没有那样使用过请求。这是我如何完成它的示例,检查结果代码并在成功时解码 JSON:

import json
import requests

action_url = "https://apiurl.example/search/"

# Prepare the headers
header_dict = {}
header_dict['Content-Type'] = 'application/json'

# make the URL request
result = requests.get(action_url, headers=header_dict)

status_code = result.status_code
if (status_code == requests.codes.ok):
    records = json.loads(result.content)
    print 'Success. Records:'
    print records
else:
    print 'ERROR. Status: {0}'.format(status_code)
    print 'headers: {0}'.format(header_dict)
    print 'action_url: {0}'.format(action_url)

    # Show the error messages.
    print result.text

推荐阅读