Openweathermap 401 error

#python #python-3.x #python-requests #openweathermap

#python #python-3.x #python-requests #openweathermap

Вопрос:

Я попытался сделать прогноз погоды на python с помощью OpenWeatherMap.org. Однако python продолжает выдавать мне ошибку о ключе API. Там написано, что он пропал.

 import requests

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

Выход-401. Я попытался вставить свой API-ключ, но он все равно не работал. И вообще, что это за API-ключ?

Комментарии:

1. Ну, ты не используешь f-строку. Таким образом, вы должны сделать это, поместив письмо f перед своим URL-адресом. Отсюда вам понадобится ваш собственный ключ API: home.openweathermap.org/users/sign_up чтобы иметь доступ к их API.

2. Это {API key} из документов openweathermap предназначено для заполнения. Вам нужно поместить туда свой фактический ключ API (» вы всегда можете найти его на странице своей учетной записи во вкладке «Ключ API» «).

3. Спасибо! Я не могу отметить ваши ответы, если вы разместите их в комментариях.

4. Ссылка

5. Я превратил свой комментарий в ответ. Кроме того, я предлагаю удалить ссылку на ваш код, в котором используется ваш фактический ключ API. Вы не должны публично делиться своими ключами API или токенами.

Ответ №1:

Это {API key} должно быть заполнителем для вашего фактического ключа API, который вы можете получить со страницы своей учетной записи openweathermap (что также означает, что вам сначала нужно будет зарегистрироваться для учетной записи). Это должно быть что-то вроде этого:

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

Печать других частей объекта ответа дала бы вам больше информации:

 In [2]: r = requests.get("https://api.openweathermap.org/data/2.5/weather?q=Londonamp;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 объяснил бы, что вам нужно предоставить действительный ключ API, и привел бы вас к их документам о том, как использовать ключи API:

Пример того, как выполнить вызов API с помощью вашего ключа API


Вызов API

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

Параметры

appid требуется
Ваш уникальный ключ API (вы всегда можете найти его на странице своей учетной записи во вкладке «Ключ API»)

@Sispheor

It was working, so something changed on their side recently.
I’ll take a look, thank you for the hint.

@Sispheor

Can you give a try by adding limit=5 to the line? So we are in free user limit ranges.

@vinpav

@Sispheor

OK, I’ll see with the lib owner if we have a workaround for this.
I can see that we are not using the last version. Maybe is already handled in the last version.

@Sispheor

Seems an issue on the API.
Do you have the same issue as this one?

@vinpav

Yes, it’s the same issue. But again, I don’t think this must be considered like a bug because the API response with a free account fits the price chart on the openweathermap website.
16 days/daily forecast API = http://api.openweathermap.org/data/2.5/forecast/daily = owm.daily_forecast(…) = requires a paid subscription.
(But, I might be misunderstanding)
Anyway, I’d be happy if there’s a way to make this work with a free account ;)

@Sispheor

ok. I don’t see any workaround to get the «tomorrow» weather with the lib.
I’m not sure this is handled so far.

@vinpav

According to what I’ve seen in the API, there is a solution to get some detailed forecast information for the next 5 days.

Using the «5 days/3 hour forecast API», available with a free account, you can get the 5 next days forcast by 3 hours periods. With good python skills (which I don’t have), it might be possible to regroup all these data day by day and compute the results : day X pressure = average pressure for that day, day X min temperature = min temperature for that day, day X precipitations = sum of precipitations for that day, etc.
Though, it seems to represent a rather huge effort for a result that would probably not be fully satisfying.

For now I’ve just commented the «tommorow» part of the neuron to make the «today» weather work.
Thanks for the feedback on this issue !

@Sispheor

Yes, I know that it’s possible to request on the api directly. The fact is taht we are using a lib to facilitate this step.
And the idea is to stick on this lib. My question was, is the lib aware of this potential change? Do we have another call that can do the trick?
I’ll check this when I have time.

Thanks for pointing out the issue.

@Sispheor

Current weather and forecast ok.
Neuron updated.

@vinpav

Same problem with V2 update of this neuron :

pyowm.exceptions.api_response_error.UnauthorizedError: Your API subscription level does not allow to perform this operation
Reason: Invalid API Key provided

I’m still using a free API key. Am I missing something ?

@Sispheor

Show us your synapse. (Cut some letters of your key)

@vinpav

- name: "weather-summary"
  signals:
      - order: "quel temps fait il"
  neurons:
      - openweathermap:
          api_key: "25xxxxxxxxxxxxxxxxxxxxxxbaa"
          lang: "fr"
          temp_unit: "celsius"
          location : "paris"
          country: "FR"
          say_template:
              - "Actuellement à {{ location }} : {{ current['weather_status'] }} avec une température de {{ current['temp'] }} degrés."

@Sispheor

looks good.
weird, no typo in the api key? a space or something?

@daylicron

I can confirm the issue.
Exception in kalliope debug log on pastebin: https://pastebin.com/5T6iZevb

I’m using up to date pyown version 2.6.1 from pip:
pip install pyowm Requirement already satisfied: pyowm in /usr/local/lib/python3.6/dist-packages (2.6.1)

My synapse:

   - name: "getthe-weather"
     signals:
       - order: "Wie wird das Wetter"
       - order: "Wie ist das Wetter"
       - order: "Wie ist das Wetter heute"
     neurons:
       - openweathermap:
           api_key: "e9ecxxxxxxxxxxxxxxxxxxxxxxxxe2d6"
           lang: "de"
           temp_unit: "celsius"
           location: "Berlin"
           country: "DE"
           say_template:
           - "Heute wird das Wetter {{ weather_today }} bei einer Temperatur von {{ temp_today_temp }} Grad."

@Sispheor

So weird, we don’t have the issue with @corus. Maybe because we have an old API key.

@vinpav

@Sispheor this is what I’ve been thinking about. Anyway, this neuron does not work for «recent» openweathermap users. Maybe you can confirm that by generating a new key / creating a new account.
I’ll switch to my previous «disappointing-current-weather-data-only» version for the moment.

@Sispheor

You are using pyowm version 2.6.1?
We’ve updated it to 2.9.0. Can you give a try?
pip install --upgrade pyown

@vinpav

I’m using pyown 2.9.0 and I have the issue.
Run your code with a recent free API key and you’ll probably reproduce this issue.

@daylicron

I’m using pyown 2.9.0 and I have the issue.

I can confirm this. Uptdating to pyowm 2.9.0 didnt’t do the trick.

@Sispheor

@corus87

I looked into it and I can confirm it seems related to our «old» keys. With a new key, I have the same problem.

With the function three_hours_forecast() I’m able to get a forecast of 5 days for every 3 hours and also weather_at_place() is working which is for the current weather conditions.

So we have to rebuild the neuron again, to make sure everyone gets the weather. I will try to make a PR till the end of the weekend.

@Sispheor

@Sispheor

I took a look to the update.
I just feel uncomfortable with the fact that it looks like a trick to keep having for free something that is now reserved to paid user.
@LaMonF what do you think?

@daylicron

I took a look to the update.
I just feel uncomfortable with the fact that it looks like a trick to keep having for free something that is now reserved to paid user.
@LaMonF what do you think?

What exactly to you mean? I checked the pricing for the OWM API and I think, things should be OK there. Take a look at the pricing. 5 days forecast and current day weather should work.

@Sispheor

We need to define clearly what we want to return. As the 5 days forecast is only for a 3 hour range.
How do we propose this as neuron input? The user provide the range of hours he wants?
We provide a dict of range and then the user take the one he wants in his template? We calculate the average from all range we got?

@daylicron

First of all I think about a switch. The user can set in the brain, if he pays for OWM or not.As default I would say, people use the free version. Using this switch we can say, that we provide the forecast the user asks for(paying users) or only the 5days/3hours forecast(free users).

Talking about what we provide for 5days/3hours forecast: How does OWM calculates the dayli forecast? I don’t know, someone who pays for OWM could find out, by comparing 5days/3 hours and dayli forecast. If they only use the max_temperature value for saying what temperature is gonna be, that should be an easy one.

But: I think it would be a nice feature to hand over the time period manually. I could imagine asking kalliope, what the weather will be in the morning. In my case this would mean: If it will be sunny/nice I’ll set my alarm 30 minutes earlier to go by bicycle to work. If it will be rainy, I’ll take the subway.

@Sispheor

New version here ready for testing.

@Sispheor

Update pushed in master branch. We’re good I think this time

@vinpav

Great ! I’ll give it a try asap.

@vinpav

Hi ! Thanks for the update on the openweathermap neuron, I have installed and tested it yesterday and it works.
However I’d like to tell you about a few things, but I don’t know if it should be considered as bugs or improvements. May we discuss it here or do I have to open a new issue ?

@Sispheor

Come on the gitter chat to discuss about it and then we can open an issue if needed.

@ghost
ghost

mentioned this issue

Nov 11, 2021

Muhammad Uzair

Error:
Invalid API key. Please see http://openweathermap.org/faq#error401 for more info

API calls responds with 401 error:
You can get the error 401 in the following cases:

  • You did not specify your API key in API request.
  • Your API key is not activated yet. Within the next couple of hours, it will be activated and ready to use.
  • You are using wrong API key in API request. Please, check your right API key in personal account.
  • You have free subscription and try to get access to our paid services (for example, 16 days/daily forecast API, any historical weather data, Weather maps 2.0, etc). Please, check your tariff in your personal account.

here are some steps to find problem.

1) Check if API key is activated

some API services provide key information in dashboard whether its activated, expired etc. openWeatherMap don’t.
to verify whether your key is working ‘MAKE API CALL FROM BROWSER’
api.openweathermap.org/data/2.5/weather?q=peshawar&appid=API_key

replace API_key with your own key, if you get data successfully then your key is activated otherwise wait for few hours to get key activated.

2) Check .env for typos & syntax

.env is file which is used to hide credentials such as API_KEY in server side code.
make sure your .env file variables are using correct syntax which is
NAME=VALUE

API_KEY=djgkv43439d90bkckcs

Enter fullscreen mode

Exit fullscreen mode

no semicolon, quotes etc

3) Check request URL

check request url where API call will be made , make sure

  • It doesn’t have spaces, braces etc
  • correct according to URL encoding
  • correct according to API documentation

4) Debug using dotenv:

to know if you dotenv package is parsing API key correctly use the following code

const result = dotenv.config()

if (result.error) {
  throw result.error
} 
console.log(result.parsed)

Enter fullscreen mode

Exit fullscreen mode

this code checks if .env file variables are being parsed, it will print API_KEY value if its been parsed otherwise will print error which occur while parsing.

Hopefully it helps :)

Here’s a comparison of different weather forecast APIs:

7 Weather Forecast API for Developing Apps

It contains a comparison of the following:

  1. Open Weather Map
  2. AccuWeather
  3. The Weather Channel
  4. Dark Sky
  5. APIXU Weather API
  6. World Weather Online
  7. Weatherbit.io

Here’s the article text:

1. Open Weather Map

The OpenWeatherMap service provides free weather data and forecast API suitable for any cartographic services like web and smartphones applications.

Ideology is inspired by OpenStreetMap and Wikipedia that make information free and available for everybody.

OpenWeatherMap provides wide range of weather data such as map with current weather, week forecast, precipitation, wind, clouds, data from weather Stations and many others. Weather data is received from global Meteorological broadcast services and more than 40 000 weather stations.

You can receive any weather data for your application by using JSON / XML API

Price: Free (See pricing details)

API: http://www.openweathermap.com/API

2. AccuWeather

AccuWeather provides premium weather forecasting services worldwide. The AccuWeather API provides subscribers access to location based weather data via a simple RESTful web interface. Data is available in more than 40 languages and dialects. Data responses are returned in JSON and JSONP. SSL encryption is also available for secure communication.

Access to the AccuWeather API requires an API key. Contact [email protected] to receive an API key.

Update: AccuWeather now offers a new API Developer Portal for easier access of the API: https://developer.accuweather.com/

Price: Premium (Contact [email protected])

API: http://api.accuweather.com/

3. The Weather Channel

The Weather Channel (weather.com) is an American satellite television channel providing weather forecast for more than 30 years. The Weather Channel and Weather Underground, Inc partnered to provide weather API with global coverage in 80 languages.

You can receive weather data for your application in JSON or XML. GIF, PNG or SWF format is also offered.

Price: Premium – Free 500 API calls per day for developing. (See pricing details)

API: http://www.wunderground.com/weather/api/?ref=twc

4. Dark Sky

The Dark Sky Company specializes in weather forecasting and visualization and they provide a developer friendly global weather forecast API with up to 1000 API calls per day for free.

The API uses a simple, JSON interface. Community-provided API wrappers enable you to integrate with just a couple lines of code.

You can use the API in both commercial and non-commercial applications. A credit with a “Powered by Dark Sky” badge is required wherever you display data from the API.

Price: Free for 1000 API calls daily, $1 per 10,000 API calls after that.

API: https://darksky.net/dev/

5. APIXU Weather API

APIXU provides a Weather API service in JSON and XML format. Their free plan has a limit of 5000 API calls per month.

They offer current weather information as well as 10 day forecast along with 30 days weather history in the free plan.

API libraries are available in all major programming languages such as C#, PHP, JAVA, Ruby, Python and JavaScript.

Price: Free for 5000 API calls monthly. Up-gradable (See Pricing)

API: https://www.apixu.com/api.aspx

6. World Weather Online

World Weather Online APIs provide a way to get local weather, historical local weather, ski and mountain weather and marine weather data. The APIs deliver weather information using standard HTTP/S requests in formats like XML, JSON and JSON-P.

They provide an API explorer for you to dive deep into their APIs. While their free plan is now discontinued, you can try their premium API for 60 days.

Code examples in all major programming languages is provided on their website, including VB.Net, PHP, Objective-C, C# etc.

Price: Premium with 60 day free trial (See Pricing)

API: https://developer.worldweatheronline.com/api/

7. Weatherbit.io

Weatherbit.io provides free weather API as well as historic weather data API. Their free plan allows 45 API calls per minute along with access to 30 days historic weather data and 5 day forecast at an update interval of 2 hours.

You would need to upgrade to a premium plan to get access to HTTPS API calls, as well to reduce the update interval to 10 mins. By upgrading you can also get access to hourly weather forecast and higher limit on API calls per minute.

Price: Free tier with premium upgrades (See Pricing)

API: https://www.weatherbit.io/api

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Openvpn ошибка сертификата
  • Openvpn ошибка подключения
  • Openvpn ошибка no server certificate verification method has been enabled
  • Openvpn ошибка 10060
  • Openvpn выдает ошибку

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии