I'm getting an error when trying to pull data from OpenWeatherMap API

Issue

I’m currently learning Flutter from an Udemy course(Lesson 146).
In this lesson, I need to use the get method from the http package. This is the code I’m using:

class Location {
  String apiKey = 'e20c545d412bb5ecc1c27b9b6afd5d37';

  Future<void> getCurrentLocation() async {
    Position position = await Geolocator.getCurrentPosition(
      desiredAccuracy: LocationAccuracy.low,
      forceAndroidLocationManager: true,
    );
    
    var data =  await get(Uri.https('api.openweathermap.org',
        '/data/2.5/weather?lat=${position.latitude}}&lon=${position.longitude}&appid=$apiKey'));
    print(data.body);
    
  }
}

and this is the error I get:

I/flutter ( 9366): {"cod":401, "message": "Invalid API key. Please
see http://openweathermap.org/faq#error401 for more info."}

Things I have tried so far:

  1. I tried to use the key on a web browser. It’s working there. I can get the JSON data with no problem whatsoever. So the key is active.
  2. I tried to change the code around, carried it into a separate dart file. No changes.

I think the problem is, I can’t send the key to the API. Or there is some sort of a syntax or a logical error that is not visible to me. So the API gives me an error about the key. Since my code doesn’t send the appropriate info.

I can’t get any progress in the course since I can’t solve this. This is the 3rd day I’m trying to fix this issue. I’m getting really frustrated. I hope someone can help me here.

Solution

Try this

var data =  await get(Uri.parse('https://api.openweathermap.org'+
    '/data/2.5/weather?lat=${position.latitude}&lon=${position.longitude}&appid=$apiKey'));

I just tested this on my machine and its working fine

It should work now.

Answered By – iamSRQansari

Answer Checked By – Timothy Miller (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *