为什么在调用 openweathermap API 时出现 401 错误 "API Key missing"?

Why do I get a 401 error "API Key missing" when calling openweathermap API?

我试图用 OpenWeatherMap.org 制作 python 天气预报。但是,python 一直给我关于 API 键 的错误。它说它丢失了。

import requests

r = requests.get("https://api.openweathermap.org/data/2.5/weather?q=London&appid={API key}")
print(r.status_code)

输出为401。我尝试输入 API 键,但仍然无效。 这个API密钥到底是什么?

{API key} 是您的 actual API 密钥的占位符,您可以从您的 openweathermap 帐户页面(这也意味着您需要先注册一个帐户)。它应该是这样的:

appid='12345678901234567890123456789012'
r = requests.get(f'https://api.openweathermap.org/data/2.5/weather?q=London&appid={appid}')

打印 other parts of the Response object 会为您提供更多信息:

In [2]: r = requests.get("https://api.openweathermap.org/data/2.5/weather?q=London&appid={API key}")

In [3]: r.status_code
Out[3]: 401

In [6]: r.content
Out[6]: b'{"cod":401, "message": "Invalid API key. Please see http://openweathermap.org/faq#error401 for more info."}'

位于http://openweathermap.org/faq#error401 would explain that you needed to provide a valid API key, and would lead you to their docs on how to use API keys的页面:

Example on how to make an API call using your API key


API call

http://api.openweathermap.org/data/2.5/forecast?id=524901&appid={API
key}

Parameters

appid required
Your unique API key (you can always find it on your account page under the "API key" tab)