Ayan Dasgupta
Ayan Dasgupta

Reputation: 704

Getting API Key Invalid error in Flutter HTTP Request

I am trying to fetch weather data from https://www.weatherapi.com/api-explorer.aspx#forecast

I have successfully generated an API key: bc4512ff6799474cbcc114118222908

In my dart file, I am trying to generate HTTP response as follows:

import 'dart:convert';

import "package:http/http.dart" as http;

String authority = "api.weatherapi.com";
String apiKey = "bc4512ff6799474cbcc114118222908";
String query = "london";
String unencodedPath =
    "v1/forecast.json?key=$apiKey&q=$query&days=10&aqi=yes&alerts=yes";

Future getWeatherData() async {
  var response = await http.get(Uri.http(authority, unencodedPath));
  var jsonData = jsonDecode(response.body);
  print(jsonData);
}

However, when I try to print the jsonData, I'm getting he following error in my terminal: {error: {code: 1002, message: API key is invalid or not provided.}}

Although, if I paste the following URL in my browser, I get a proper json response: https://api.weatherapi.com/v1/forecast.json?key=bc4512ff6799474cbcc114118222908&q=London&days=10&aqi=yes&alerts=yes

enter image description here

What is wrong in my code, and how to solve the issue?

Upvotes: 0

Views: 877

Answers (1)

eamirho3ein
eamirho3ein

Reputation: 17950

try this:

String authority = "api.weatherapi.com";
String apiKey = "bc4512ff6799474cbcc114118222908";
String query = "london";
String unencodedPath = "v1/forecast.json";

final queryParameters = {
  'key': apiKey,
  'q': query,
  'days': 10,
  'aqi': 'yes',
  'alerts': 'yes',
  
};


Future getWeatherData() async {
  final uri = Uri.https(authority, unencodedPath, queryParameters);
 
  var response = await http.get(uri);;
  var jsonData = jsonDecode(response.body);
  print(jsonData);
}

Upvotes: 2

Related Questions