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

Time:05-11

Hello i want to access an API with Python but it's not working. I get this json file:

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

My code:

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)

But when i access the API on my browser it works: https://api.henrikdev.xyz/valorant/v2/match/06a29aa4-7862-4d6b-85f7-1fda200386f1

CodePudding user response:

It's working smoothly. You have to just inject user-agent as 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)
   
  • Related