PAbleBoo
PAbleBoo

Reputation: 65

How to make HTTP request in Dart with params and header (Uri)

I am new to Flutter. I wanted to get a request from a API from the website https://rapidapi.com/. Please help me to translate the Python to Dart.

I am able to get the total data using the link https://covid-19-data.p.rapidapi.com/totals in place of uri, but unable to get country data by passing the name of the country.

This is a Python Code and i want this in Dart(Flutter)

import requests

url = "https://covid-19-data.p.rapidapi.com/country"

querystring = {"format":"undefined","name":"italy"}

headers = {
    'x-rapidapi-host': "covid-19-data.p.rapidapi.com",
    'x-rapidapi-key': "84768ddbd5mshe582f65a69666d5p1fea75jsn3a2b9202cc14"
    }

response = requests.request("GET", url, headers=headers, params=querystring)

print(response.text)

This is what i did in Dart. I get the Error

{"type":"https:\/\/tools.ietf.org\/html\/rfc2616#section-10","title":"An error occurred","detail":"Parameter name is missing"}

The Status Code is 400.

import 'package:flutter/cupertino.dart';
import 'package:http/http.dart' as http;

class NetworkingBrain {
  NetworkingBrain({@required this.params});

  final params;

  Future<void> getData() async {
    try {
      var value = {'country1': params};
      var uri = Uri.parse('https://covid-19-data.p.rapidapi.com/country')
          .replace(queryParameters: value)
          .toString();

      http.Response response = await http.get(uri, headers: {
        'x-rapidapi-host': "covid-19-data.p.rapidapi.com",
        'x-rapidapi-key': "84768ddbd5mshe582f65a69666d5p1fea75jsn3a2b9202cc14"
      });
      print(response.body);
      print(response.statusCode);
    } catch (e) {
      print(e);
    }
  }
}

Please help me with this.

Upvotes: 0

Views: 1167

Answers (2)

ibhavikmakwana
ibhavikmakwana

Reputation: 10161

You are passing a wrong parameter.

Pass name as a key

As below:

   var value = {'name': params};

instead of

  var value = {'country1': params};

Upvotes: 1

Ujas Patel
Ujas Patel

Reputation: 63

You need to decode json file after getting response. try using following code.

Map data;
List userData;
http.Response response = await http.get(uri, headers: {
    'x-rapidapi-host': "covid-19-data.p.rapidapi.com",
    'x-rapidapi-key': "84768ddbd5mshe582f65a69666d5p1fea75jsn3a2b9202cc14"
  });
data = json.decode(response.body);
setState(() {
  userData = data['tag of json file'];

});

}

Upvotes: 1

Related Questions