Пробую сделать запрос на OpenWeather, но выдает ошибку 401
import requests
api_weather_city = "http://api.openweathermap.org/geo/1.0/direct?q="
api_key = "***https://openweathermap.org/api/one-call-3 Получить api тут***"
def get_cityForWeather(city, responses=1):
url = f"{api_weather_city}{city}&limit={responses}&appid={api_key}"
response = requests.get(url)
if response.status_code == 200:
city_data = response.json()
return city_data
else:
print(f"Failed {response.status_code}")
return None
# Получение данных о городе
city_weather = get_cityForWeather("London", 5)
if city_weather and len(city_weather) > 0:
# Получаем первый результат из списка
city = city_weather[0]
lat = city["lat"] # Широта
lon = city["lon"] # Долгота
else:
print("Город не найден.")
# Получение погоды по координатам
def get_Weather(lat, lon):
url = f"https://api.openweathermap.org/data/3.0/onecall?lat={lat}&lon={lon}&appid={api_key}&units=metric"
response = requests.get(url)
if response.status_code == 200:
weather_data = response.json()
return weather_data
else:
print(f"Failed {response.status_code}")
return None
# Запрос на получение погоды
getting_weather = get_Weather(lat, lon)
if getting_weather:
# Погодные данные находятся в ключе 'current', а информация о погоде в списке 'weather'
weather = getting_weather.get("current", {}).get("weather", [])
if weather:
# Печатаем описание погоды
print(f"Текущее состояние погоды: {weather[0].get('description', 'Неизвестно')}")
else:
print("Информация о погоде не найдена.")
else:
print("Ошибка получения погоды.")
Ответы (1 шт):
Автор решения: ykoavlil
→ Ссылка
Документация тут: https://openweathermap.org/api/geocoding-api
Упростил код, чтобы чисто проверить токен:
import requests
geocoding = requests.get(
url='http://api.openweathermap.org/geo/1.0/direct',
params={
'q': 'London',
'limit': 1,
'appid': 'Указать api_key'
}
)
print(geocoding.status_code)
print(geocoding.json())
Фрагмент ответа:
[
{
"name": "London",
"local_names":
{
"nn": "London",
"lo": "ລອນດອນ",
"sr": "Лондон",
...
},
"lat": 51.5073219,
"lon": -0.1276474,
"country": "GB",
"state": "England"
}
]
Возможные причины ошибки перечислены тут: https://openweathermap.org/faq#error401
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 are using a Free subscription and try requesting data available in other subscriptions . For example, 16 days/daily forecast API, any historical weather data, Weather maps 2.0, etc). Please, check your subscription in your personal account.