Search code examples
pythonjsonhttprequesturllib

Getting 403 Forbidden error when requesting JSON output with apikey


I am trying to request information from a server with Python. The API key is correct however I still get the 403 error. It works with curl, but not with Python.

Here is the curl code that outputs JSON:

curl -H "apiKey: xxx" https://kretaglobalmobileapi.ekreta.hu/api/v1/Institute/3928

And here is my code that outputs Forbidden error:

from urllib.request import Request, urlopen 
import json
ker = Request('https://kretaglobalmobileapi.ekreta.hu/api/v1/Institute/3928')
ker.add_header('apiKey', 'xxxx')
content = json.loads(urlopen(ker))
print(content)

What is the problem?


Solution

  • urlopen usually returns a HTTPResponse object. So in order to read the contents use the read() function. Other wise your code looks fine.

    req = Request('https://kretaglobalmobileapi.ekreta.hu/api/v1/Institute/3928')
    req.add_header('apikey', 'xxx')
    content = urlopen(req).read()
    
    print(content).
    

    You can also use another library for instance requests if the above method dosent work,

    r = requests.get('<MY_URI>', headers={'apikey': 'xxx'})