Suraj S Jain
Suraj S Jain

Reputation: 535

Flutter HTTP GET request not working with body as a parameter

I have a REST API that takes in a GET request with a JSON body as:

{
    "cart_only_items": true
}

and the head as:

{
      "Authorization": "Token my_auth_token",
}

and returns a response as:

{
    "items": [...]
}

This REST API's GET request works just fine on postman.

So, I tried to implement this request in Flutter as follows:

import 'package:http/http.dart';
import 'dart:convert';

void getCart() async {
    Map<String, String> reqHead = {
      "Authorization": "Token my_auth_token",
    };
    Map<String, dynamic> reqBody = {"cart_only_items": true};
    String reqURL = "${my_base_url}details/";
    Response res = await get(
      reqURL,
      body: jsonEncode(reqBody),
      headers: reqHead,
    );
  }

But in the above code, I got a dart analysis error like:

error: The named parameter 'body' isn't defined. (undefined_named_parameter at [shoppingapp] lib/pages/Cart.dart:39)

So, what's the right way to make a GET request to a REST API that requires a JSON input using Flutter?

Upvotes: 1

Views: 8740

Answers (3)

Destiny Maina
Destiny Maina

Reputation: 71

Sometimes you have no control over the API GET endpoints that require some data. Here's the hack:

Add the data as parameters to the URL. For example:

String reqURL = "${my_base_url}details?user_id=${user.id}";

Upvotes: 0

Aditya Joshi
Aditya Joshi

Reputation: 1053

This is because, GET request is not allowed to pass any kind of data in the body. To pass data you have to use POST request or query parameters in GET request.


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

void getCart() async {

Map data = {
  'key1': 1,
  'key2': "some text"
}

String body = json.encode(data);

http.Response response = await http.post(
  url: 'https://example.com',
  headers: {"Content-Type": "application/json"},
  body: body,
);

}

Upvotes: 4

Bill_The_Coder
Bill_The_Coder

Reputation: 2510

Try

body: json.decode(reqBody.body),

instead of body: jsonEncode(reqBody) in your code.

Upvotes: 0

Related Questions