简体   繁体   English

Python要求NewsAPI每次响应401

[英]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. 我正在尝试在python程序中使用News API ,由于某种原因,无论如何我都无法获得200条响应。 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. 并且输出始终为401。但是奇怪的是,如果我只是在浏览器中放置“ https://newsapi.org/v1/articles/?source=google-news&apiKey=XXXXXXXXX ”,它会给出正确的json响应,因此我使用请求的方式一定有问题。

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. 确实可行,但我仍然想知道如何在将来正确使用请求包。

Based on the 'working' link provided, it expects URL parameters, not headers on its request, so: 根据提供的“工作”链接,它需要URL参数,而不是请求头,因此:

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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM