为什么我不能用 Python 访问 API,但我可以用我的浏览器访问?

Why i can't access an API with Python, but i can do it with my Browser?

您好,我想使用 Python 访问 API,但它不起作用。我得到这个 json 文件:

{"status": 403, "message": "Forbidden"}

我的代码:

result = requests.get(f"https://api.henrikdev.xyz/valorant/v2/match/06a29aa4-7862-4d6b-85f7-1fda200386f1").json()
with open("result.json", "w") as f:
    json.dump(result, f)

但是当我在浏览器上访问 API 时它起作用了:https://api.henrikdev.xyz/valorant/v2/match/06a29aa4-7862-4d6b-85f7-1fda200386f1

一切顺利。您只需将 user-agent 注入为 header

import requests
import json
headers={'User-Agent':'mozilla/5.0'}
result = requests.get(f"https://api.henrikdev.xyz/valorant/v2/match/06a29aa4-7862-4d6b-85f7-1fda200386f1",headers=headers).json()
jdata =  json.dumps(result,indent=4)
with open("result.json", "w") as f:
    f.write(jdata)