delmin
delmin

Reputation: 2690

Send JSON body with HTTP get request

I'm trying to put JSON body query parameters into http.get request. I tried to even follow this Flutter: Send JSON body for Http GET request but no luck there. No matter what I put into params variable I get all results from my backend. I have tested backend with postman and everything works fine

enter image description here

Here is my code in flutter

 Future<List<Country>> fetchCountries(String name) async {
    final token = Provider.of<Auth>(context, listen: false).token;
    final params = {"name": "Uk"};
    try {
      Uri uri = Uri.parse(APIPath.findCountry());
      final newUri = uri.replace(queryParameters: params);
      print(newUri); //prints http://localhost:8080/country/find?name=uk
      final response = await http.get(newUri,
          headers: [APIHeader.authorization(token), APIHeader.json()]
              .reduce(mergeMaps));
      final jsonResponse = json.decode(response.body);
      if (response.statusCode == 200) {
        Iterable list = jsonResponse['result'];
        print(list);
        return list.map((model) => Country.fromJson(model)).toList();
      } else {
        throw HttpException(jsonResponse["error"]);
      }
    } catch (error) {
      throw error;
    }
  }

Placing body into http.get request doesn't work as for http.post request. Any idea what am I doing wrong?

Upvotes: 6

Views: 13780

Answers (1)

mentallurg
mentallurg

Reputation: 5207

There are several things to keep in mind.

  1. The HTTP RFC for method GET says:

A payload within a GET request message has no defined semantics...

It is a bad architectural style, to send any data in the body of GET request.

  1. If you want to ignore that and still want to send body in the GET request, it makes sense to set content type header to "application/json".

  2. The example you referred does not use body in the GET request. Instead, it retrieves parameter values from the given JSON object and puts them to a URL. Then this URL is called via GET without body.

My suggestion:

  • If the number of URL parameters is relatively small and their values are short, so that the resulting URL is readable, use GET and URL with parameters.
  • If the URL with parameters becomes hard to read, put parameters to the body and use POST.
  • There are no precise criteria. It is a matter of your taste and your personal preferences. The readability of URL may be just one of criteria to consider when choosing GET or POST.

Upvotes: 3

Related Questions