REST API通过curl可正常调用,但使用requests库调用失败
Python调用OpenSubtitles下载API失败,但curl请求正常
问题详情
我用Python的requests库调用OpenSubtitles的下载API,代码如下:
import requests url = "https://api.opensubtitles.com/api/v1/download" payload = {"file_id": id_to_download} headers = { "Content-Type": "application/json", "Api-Key": "myApiKey", "Authorization": "Bearer myApiKey" } response = requests.request("POST", url, json=payload, headers=headers) print(response.text)
请求返回错误:
{ "message":"You cannot consume this service" }
但用curl调用相同接口却能正常返回结果:
curl --request POST --header 'Api-Key: myApiKey' --url https://api.opensubtitles.com/api/v1/download --header 'Content-Type: application/json, Authorization: Bearer undefined' --data '{"file_id": 934267}'
返回结果(包含配额信息,说明与配额无关):
{"link":"https://www.opensubtitles.com/download/901E4D16AF81FF191D37B3D10AD6517A2ECE30F77679205199EF4742C5595022275ADBA60A53E73F444E251FA5B71825CA101C199D469B02264AFCCC46F1AAAF966A8197FA479E70CC58EE2D1D89FFCB04226FB33DCECBBB3BFF04F888E5CAC73C8D9813FCF84245B7AC80F9B5B18E386524F881292F0EFE45A534879E2AC7D6B92BB55BF6F5E948F6D1A586809E5723BFDA861BB0E6E842AAFB71D5A74ADC9BFB95C067D7B853C9BA2C5819726E5D90536DA0AC9EBB282602133CBECF24E1DDC1337731FEB652A384059CA4D5452F62FC4325C7D75BDA6B9AE06CCE34A1DA872B15DD28BD0D90C548BB122C38ADF8267DA29F7418C8C5F6BDD3A423F8CC20904BC2D8960A1C0C9B30A9CE0EFDC65CCBC696EE74666CE631B17F1139C7D95507CFCAAF65B5D4370C/subfile/Magic.Mike.XXL.2015.720p.BluRay.x264-GECKOS.srt","file_name":"Magic.Mike.XXL.2015.720p.BluRay.x264-GECKOS.srt","requests":8,"remaining":92,"message":"Your quota will be renewed in 16 hours and 06 minutes (2022-10-24 01:25:09 UTC) ","reset_time":"16 hours and 06 minutes","reset_time_utc":"2022-10-24T01:25:09.000Z"}
另外,调用其他如subtitles的GET接口时,用requests库能正常工作:
url = "https://api.opensubtitles.com/api/v1/subtitles" querystring = {"query": movie_name, "languages": "en"} headers = { "Content-Type": "application/json", "Api-Key": "myApiKey" } response = requests.request("GET", url, headers=headers, params=querystring) print(response.text)
问题原因
对比curl和Python代码的请求头可以发现:
- curl请求中
Authorization头的值是Bearer undefined,这个无效值实际相当于未传递有效授权令牌,但请求依然成功 - Python代码中错误地将
Api-Key作为Bearer令牌放在Authorization头里,导致API验证失败,返回无法使用服务的错误
OpenSubtitles的下载API并不需要Authorization头(从curl的成功请求可验证),额外传递错误的Authorization信息反而会触发API的权限拦截。
解决方法
修改Python代码的headers,移除多余的Authorization字段即可:
import requests url = "https://api.opensubtitles.com/api/v1/download" payload = {"file_id": id_to_download} headers = { "Content-Type": "application/json", "Api-Key": "myApiKey" } response = requests.request("POST", url, json=payload, headers=headers) print(response.text)
内容的提问来源于stack exchange,提问作者yPhil
相关产品推荐
相关产品推荐

