0

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?

1 Answer 1

2

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);
}
Sign up to request clarification or add additional context in comments.

4 Comments

String authority = "api.weatherapi.com/"; doing this causes a FormatExceptionError.
I updated my answer, check it out.
add / to the start of unencodedPath.
Still the same API invalid error even after puttong / before v1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.