Python调用GitHub示例Simple Books API报bookId无效400错误求助
问题根因
接口要求接收JSON格式的请求体,你当前代码的传参方式不符合要求:
- 调用
requests.post()时传入data参数传字典,requests默认会将字典编码为application/x-www-form-urlencoded格式的表单数据,后端无法从JSON请求体中解析到int类型的bookId字段,因此返回"Invalid or missing bookId"错误。 - Postman、cURL发起JSON请求时会自动完成参数序列化、设置正确的
Content-Type请求头,因此可以正常调用。
修复方法
优先选第一种改法,代码更简洁:
方法一:使用json参数传参(推荐)
将data参数替换为json参数,requests会自动完成字典到JSON的序列化,同时自动添加Content-Type: application/json请求头,无需额外手动处理:
import requests order_url = "https://simple-books-api.glitch.me/orders" my_post_1 = {"bookId" : 1, "customerName" : "Anna"} header_1 = {"Authorization" : my_token} # 替换data为json参数 post_text_1 = requests.post(order_url, json=my_post_1, headers=header_1) # 修正状态码打印逻辑,直接打印响应对象无法得到正确的HTTP状态码 print("status:", post_text_1.status_code) print("response:", post_text_1.text)
方法二:手动序列化JSON参数
如果要保留data参数的写法,需要手动将字典序列化为JSON字符串,同时在请求头中明确声明内容类型为JSON:
import requests import json order_url = "https://simple-books-api.glitch.me/orders" my_post_1 = {"bookId" : 1, "customerName" : "Anna"} header_1 = { "Authorization": my_token, "Content-Type": "application/json" } # 手动序列化字典为JSON字符串再传入data参数 post_text_1 = requests.post(order_url, data=json.dumps(my_post_1), headers=header_1) print("status:", post_text_1.status_code) print("response:", post_text_1.text)
补充说明
你原有代码打印状态码的写法有误,直接打印post_text_1得到的是响应对象的字符串表示,不是实际的HTTP状态码,需要调用响应对象的.status_code属性才能拿到200、400这类标准状态码。
内容的提问来源于stack exchange,提问作者finn
相关产品推荐
相关产品推荐

