用Python向本地REST API发POST请求遇JSONDecodeError,该如何解决?
问题:POST请求本地REST API时出现JSON解码错误
问题现象
向本地部署的REST API发送POST请求时,持续报错:
requests.exceptions.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
原实现代码
import requests import json def create_bucket(): url = "http://127.0.0.1:3000/api/buckets" headers = { "content-type": "application/json" } params = { "bucket_name": "test_bucket" } response = requests.post(url=url, headers=headers, params=params) print(response.json()) create_bucket()
排查信息
打印response.content后,得到API返回的400错误:
b'<!doctype html>\n<html lang=en>\n<title>400 Bad Request</title>\n<h1>Bad Request</h1>\n<p>Failed to decode JSON object: Expecting value: line 1 column 1 (char 0)</p>\n'
问题原因
原代码错误使用了params参数传递数据——params会将数据拼接为URL的查询字符串,而非放入请求体中。但请求头声明了content-type: application/json,API期望从请求体获取JSON格式的请求数据,因此无法解析到有效JSON内容,返回400错误;同时本地尝试解析空/非JSON响应时,抛出JSONDecodeError。
解决方法
将数据转为JSON字符串放入请求体,正确写法如下:
response = requests.post(url=url, headers=headers, data=json.dumps(params))
更简洁的写法是直接使用requests的json参数,它会自动将字典编码为JSON字符串,并设置正确的Content-Type头(此时可省略手动定义的headers):
response = requests.post(url=url, json=params)
内容的提问来源于stack exchange,提问作者roqou
相关产品推荐
相关产品推荐

