Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using OpenWeatherMap API gives 401 error

I'm trying to get the weather data for London in JSON but I am getting HTTPError: HTTP Error 401: Unauthorized. How do I get the API working?

import urllib2
url = "http://api.openweathermap.org/data/2.5/forecast/daily?q=London&cnt=10&mode=json&units=metric"
response = urllib2.urlopen(url).read()
like image 856
hky404 Avatar asked Oct 12 '15 23:10

hky404


2 Answers

The docs open by telling you that you need to register for an API key first.

To access the API you need to sign up for an API key

Since your url doesn't contain a key, the site tells you you're not authorized. Follow the instructions to get a key, then add it to the query parameters.

http://api.openweathermap.org/data/2.5/forecast/daily?APPID=12345&q=...
like image 175
davidism Avatar answered Sep 28 '22 11:09

davidism


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]([price and condition]).

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

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)

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 :)

like image 44
Muhammad Uzair Avatar answered Sep 28 '22 13:09

Muhammad Uzair