Zaya Zaya - 2 months ago 16
Python Question

Python Requests for NewsAPI reponding 401 every time

I'm trying to use the News API in a python program, and for some reason I can't get a 200 response no matter what. I'm pretty unfamiliar with the requests library, so maybe I'm not doing something right, but here's what my code looks like:


def get_json_response(apiKey, resource='google-news', sortBy='latest'):
url = ''
headers = { 'source': resource,
'apiKey': apiKey,
'sortBy': sortBy}

r = requests.get(url, headers=headers)


and the output is always 401.
But what's weird is if i just put "" in a browser, it gives the correct json response, so it has to be something wrong with how I'm using requests.

Any ideas? Thanks in advance

Not exactly an elegant solution, but i switched the line to:

r = requests.get(url + '/?source=' + resource + '&sortBy=' + sortBy + '&apiKey=' + apiKey)

And that worked, but I'd still like to know how to use the requests package correctly for the future.

Answer Source

Based on the 'working' link provided, it expects URL parameters, not headers on its request, so:

def get_json_response(apiKey, resource='google-news'):
    url = ''
    params = {'source': resource,
              'apiKey': apiKey}
    r = requests.get(url, params=params)
    # etc.