DEV Community

Muhammad Uzair
Muhammad Uzair

Posted on

5

Solve problem of API responds with 401 error

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:

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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay