You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python requests API调用遇AttributeError:'str'对象无json属性如何解决?

问题描述

我参考相关线程编写了以下Python脚本,使用凭证进行API调用,但执行时打印j得到None,还出现了AttributeError: 'str' object has no attribute 'json'错误,请问该如何解决?

脚本代码

import requests

username = 'johndoe'
password= 'zznAQOoWyj8uuAgq'

headersAuth = {
    'accept': 'application/json',
    'Content-length': ''
}

data = {'username': username,'password': password}

## Authentication request

response = requests.post('https://somedomain.test.com/token', headers=headersAuth, data=data, verify=True)
j = response.json()
print(j)

headersAPI = {
    'accept': 'application/json',
    'Content-length': '',
    'Authorization': j['access_token']
}

# Making sample API call with authentication and API parameters data

response = requests.get('https://somedomain.test.com/api/Users/Year/2020/Workers', headers=headersAPI, verify=True)
api_response = response.json()

报错信息

j = response.json()
AttributeError: 'str' object has no attribute 'json'
解决方法

1. 修复变量覆盖问题

你在第二个请求中把返回结果重新赋值给了response变量,覆盖了之前requests.post返回的Response对象,导致后续调用.json()时,实际是对字符串调用方法,直接报错。把第二个请求的变量名改成其他名称即可:

# 替换原GET请求代码
api_response_obj = requests.get('https://somedomain.test.com/api/Users/Year/2020/Workers', headers=headersAPI, verify=True)
api_response = api_response_obj.json()

2. 移除无效请求头

你手动设置了空字符串的Content-length,这会干扰requests库自动处理请求头的逻辑,直接删掉这个键值对:

headersAuth = {
    'accept': 'application/json'
}

headersAPI = {
    'accept': 'application/json',
    'Authorization': f"Bearer {j['access_token']}"  # 注意:多数API要求Bearer前缀
}

3. 添加请求状态校验

先确认认证请求是否成功,避免在请求失败时强行解析JSON:

response = requests.post('https://somedomain.test.com/token', headers=headersAuth, data=data, verify=True)
# 先判断请求是否成功
if response.status_code == 200:
    j = response.json()
    print(j)
else:
    print(f"认证请求失败,状态码:{response.status_code},响应内容:{response.text}")
    exit(1)

4. 补全认证头格式

绝大多数使用Bearer Token的API要求头格式为Bearer <token>,必须在token前加上Bearer 前缀,否则API会识别为无效认证信息。

内容的提问来源于stack exchange,提问作者Josh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 07:09:19