23

I need to make a GET request to an API from my Flutter app which requires request body as JSON (raw).

I tested the API with JSON request body in Postman and it seems to be working fine.

enter image description here

Now on my Flutter application I am trying to do the same thing:

_fetchDoctorAvailability() async {
    var params = {
      "doctor_id": "DOC000506",
      "date_range": "25/03/2019-25/03/2019" ,
      "clinic_id":"LAD000404"
    };

    Uri uri = Uri.parse("http://theapiiamcalling:8000");
    uri.replace(queryParameters: params);

    var response = await http.get(uri, headers: {
      "Authorization": Constants.APPOINTMENT_TEST_AUTHORIZATION_KEY,
      HttpHeaders.contentTypeHeader: "application/json",
      "callMethod" : "DOCTOR_AVAILABILITY"
    });

    print('---- status code: ${response.statusCode}');
    var jsonData = json.decode(response.body);

    print('---- slot: ${jsonData}');
}

However the API gives me an error saying

{message: Missing input json., status: false}

How do I send a raw (or rather JSON) request body for Http GET request in Flutter?

codeinprogress
  • 3,193
  • 7
  • 43
  • 69

5 Answers5

27

GET

GET requests are not intended for sending data to the server (but see this). That's why the http.dart get method doesn't have a body parameter. However, when you want to specify what you are getting from the server, sometimes you need to include query parameters, which is a form of data. The query parameters are key-value pairs, so you can include them as a map like this:

final queryParameters = {
  'name': 'Bob',
  'age': '87',
};
final uri = Uri.http('www.example.com', '/path', queryParameters);
final headers = {HttpHeaders.contentTypeHeader: 'application/json'};
final response = await http.get(uri, headers: headers);

POST

Unlike GET requests, POST requests are intended for sending data in the body. You can do it like this:

final body = {
  'name': 'Bob',
  'age': '87',
};
final jsonString = json.encode(body);
final uri = Uri.http('www.example.com', '/path');
final headers = {HttpHeaders.contentTypeHeader: 'application/json'};
final response = await http.post(uri, headers: headers, body: jsonString);

Note that the parameters were a Map on the Dart side. Then they were converted to a JSON string by the json.encode() function from the dart:convert library. That string is the POST body.

So if the server is asking you to pass it data in a GET request body, check again. While it is possible to design a server in this way, it isn't standard.

Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
10

uri.replace... returns a new Uri, so you have to assign it into a new variable or use directly into the get function.

final newURI = uri.replace(queryParameters: params);

var response = await http.get(newURI, headers: {
  "Authorization": Constants.APPOINTMENT_TEST_AUTHORIZATION_KEY,
  HttpHeaders.contentTypeHeader: "application/json",
  "callMethod" : "DOCTOR_AVAILABILITY"
});

using post:

      var params = {
        "doctor_id": "DOC000506",
        "date_range": "25/03/2019-25/03/2019" ,
        "clinic_id":"LAD000404"
      };

      var response = await http.post("http://theapiiamcalling:8000", 
      body: json.encode(params)
      ,headers: {
        "Authorization": Constants.APPOINTMENT_TEST_AUTHORIZATION_KEY,
        HttpHeaders.contentTypeHeader: "application/json",
        "callMethod" : "DOCTOR_AVAILABILITY"
      });
diegoveloper
  • 93,875
  • 20
  • 236
  • 194
2

You can use Request class as following:

var request = http.Request(
  'GET',
  Uri.parse("http://theapiiamcalling:8000"),
)..headers.addAll({
    "Authorization": Constants.APPOINTMENT_TEST_AUTHORIZATION_KEY,
    HttpHeaders.contentTypeHeader: "application/json",
    "callMethod": "DOCTOR_AVAILABILITY",
  });
var params = {
  "doctor_id": "DOC000506",
  "date_range": "25/03/2019-25/03/2019",
  "clinic_id": "LAD000404"
};
request.body = jsonEncode(params);
http.StreamedResponse response = await request.send();
print(response.statusCode);
print(await response.stream.bytesToString());

Also, note that Postman that can convert an API request into a code snippet in more than 15 languages. If you select Dart, you will find a similar code to above.

Hasan El-Hefnawy
  • 1,249
  • 1
  • 14
  • 20
0

It may help someone those who used Getx for api integration . We can use request method for these kind of requirement.

 Map<String, dynamic>  requestBody = { 'id' : 1};
 Response<Map<String, dynamic>> response =
      await request(url, 'get', body: requestBody);
Saranya Subramanian
  • 417
  • 1
  • 5
  • 19
-2

if you want to send complex/nested data through a GET request like the sample below, you can use a simple class i created on github https://github.com/opatajoshua/SimplifiedUri

final params = {
  'name': 'John',
  'columns': ['firstName', 'lastName'],
  'ageRange': {
    'from': 12,
    'to': 60,
  },
  'someInnerArray': [1,2,3,5]
};
final Uri uri = SimplifiedUri.uri('http://api.mysite.com/users', params);
final headers = {HttpHeaders.contentTypeHeader: 'application/json'};
final response = await http.get(uri, headers: headers);

output

http://api.mysite.com/users?name=John&columns%5B%5D=firstName&columns%5B%5D=lastName&ageRange%5Bfrom%5D=12&ageRange%5Bto%5D=60&someInnerArray%5B%5D=1&someInnerArray%5B%5D=2&someInnerArray%5B%5D=3&someInnerArray%5B%5D=5

Joshua Opata
  • 533
  • 5
  • 8