Python调用USAspending API返回422错误,如何调整请求代码?
问题原因
- 核心错误是请求参数传递方式不符合接口要求:
/api/v2/search/spending_by_award为POST类型接口,要求查询条件以JSON格式放在请求体中,你代码中使用params参数传递数据,会把所有条件拼接为URL后缀的查询字符串,接口无法识别这类格式的参数,因此返回422状态码。 - 额外可优化点:可以在请求后打印响应的错误信息,方便定位具体参数问题。
修改方案
把requests.post的入参从params=criteria改为json=criteria即可,requests会自动把字典序列化为JSON格式放在请求体中,同时自动设置正确的Content-Type: application/json请求头。
修改后的完整代码如下:
import requests url = "https://api.usaspending.gov" endpoint = "/api/v2/search/spending_by_award" criteria = { "filters": { "award_type_codes": ["10"], "agencies": [ { "type": "awarding", "tier": "toptier", "name": "Social Security Administration" }, { "type": "awarding", "tier": "subtier", "name": "Social Security Administration" } ], "legal_entities": [779928], "recipient_scope": "domestic", "recipient_locations": [650597], "recipient_type_names": ["Individual"], "place_of_performance_scope": "domestic", "place_of_performance_locations": [60323], "award_amounts": [ { "lower_bound": 1500000.00, "upper_bound": 1600000.00 } ], "award_ids": [1018950] }, "fields": ["Award ID", "Recipient Name", "Start Date", "End Date", "Award Amount", "Awarding Agency", "Awarding Sub Agency", "Award Type", "Funding Agency", "Funding Sub Agency"], "sort": "Recipient Name", "order": "desc" } # 仅修改这一行,把params改为json response = requests.post(f"{url}{endpoint}", json=criteria) print(response.status_code) # 出现问题时可以打印响应内容排查具体错误 print(response.json())
内容的提问来源于stack exchange,提问作者user16022131
相关产品推荐
相关产品推荐

