3

I'm trying to make an API call to OpenWeatherMap. When I execute flutter run in the terminal, the response.statusCode prints 401 which is code for Invalid API Key, although I have generated the API Key in an appropriate way and it is active and copied correctly.

const APIKey = '69f9afe03f52ef5c83887fc86dd79d99';

  void getData() async {
    http.Response response = await http.get(Uri.parse('https://api.openweathermap.org/data/3.0/onecall?lat=$latitude&lon=$longitude&appid=$APIKey'));
    if (response.statusCode == 200) {
      String data = response.body;
      var decodedData = jsonDecode(data);
      print(decodedData);
    } else {
      print(
        response.statusCode,
      );
    }
  }

Geolocator package for Flutter was used to assign the Latitude and Longitude. How can the 401 Error be rectified?

4 Answers4

5

checkout Using OpenWeatherMap API gives 401 error here you will find some reasons why your apikey is not working. also, it takes 2 hours for key activation.

Ninad7N
  • 544
  • 4
  • 13
  • I have waited for more than 2 hours and it still shows the same thing –  Jun 17 '22 at 10:43
  • 1
    I think that waiting is likely the answer for most people who've double checked and ensured they're following the API documentation. For mine to become active, I had to wait well more than 2hrs - eventually gave up for the night and just tried again in the morning, at which time it worked. – mattezell Jan 31 '23 at 04:55
2

Might be a bit late to reply, but the URL you are using is no longer part of the free plan and that's why you get that error. Try using the following URL, it requires the user to input a city name and there is no need of using latitude and longitude.

https://api.openweathermap.org/data/2.5/weather?q=${*cityName*}&appid=${*API_key*}&units=metric

So, if you have a text field that takes the input for a city name, then the above fetch call would work.

Here cityName is the location entered by the user and API_key is the API key you are assigned. By having &units=metric, you will get the temperature in degree Celcius. If you want the temperature in Farenheit, use &units=imperial or if you want the temperature in Kelvin, just get rid of the &units=metric part.

So for example if you paste the following in your browser, you will get the weather in London.

api.openweathermap.org/data/2.5/weather?q=London&APPID=YOUR_API_KEY

Hope my first answer on this platform helps somebody.

0

Go to the website and generate new api key by deleting the previous one.

You can generate as many api keys as required.

0

for openweather map if you are a new user and just generated your api key then its take 45 minutes to activate your key