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:

api = XXXXXXXXXX

def get_json_response(apiKey, resource='google-news', sortBy='latest'):
url = 'https://newsapi.org/v1/articles'
headers = { 'source': resource,
'apiKey': apiKey,
'sortBy': sortBy}

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

get_json_response(api)


and the output is always 401.
But what's weird is if i just put "https://newsapi.org/v1/articles/?source=google-news&apiKey=XXXXXXXXX" 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

EDIT:
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 = 'https://newsapi.org/v1/articles/'
    params = {'source': resource,
              'apiKey': apiKey}
    r = requests.get(url, params=params)
    print(r.status_code)
    # etc.