Abhishek Kumar
Abhishek Kumar

Reputation: 45

How to add a body to GET request in dart/flutter?

I'm trying to get a response from an API that requires a body with the GET request. It works fine with POSTMAN because it allows us to add body to GET request. But how to add GET request using dart?

Upvotes: 0

Views: 2852

Answers (3)

craystern
craystern

Reputation: 55

You'll have to write your custom BaseClient or BaseRequest using http package. That's how the bare minimum, for creating client with custom get method, would look like:

import 'package:http/http.dart' as http; 
// don't forget to add packages to pubspec.yaml too

class CustomClient extends http.BaseClient {
  final _inner = http.Client();
  CustomClient() : super();

  send(http.BaseRequest request) {
    return _inner.send(request);
  }

  Future<http.StreamedResponse> getWithBody
      (Uri url, Map<String, dynamic> bodyParams) {    

    final _request = http.Request("GET", url);
    _request.body = jsonEncode(bodyParams);
    _request.bodyBytes = utf8.encode(_request.body);

    return this.send(_request);
  }
}

You can do more to BaseClient than that, like adding custom User-Agent header:

import 'package:package_info_plus/package_info_plus.dart';

  send(http.BaseRequest request) async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    request.headers['user-agent'] = 
        "${packageInfo.appName}/${packageInfo.version}";
    request.headers['content-type'] = "application/json";
    return _inner.send(request);
  }

or hardwiring your client to address of your particular API, and further customising .get method:

enum EntityType { degree, teacher, room }

class CustomClient extends http.BaseClient {
  final String serverAdress = "example.com";
  final String apiPath = "/api";
  // [...]

  Future<http.StreamedResponse> getActivityList(EntityType entity, int entityId) {
    String path;
    switch(entity) {
      case EntityType.degree:
        path = apiPath + "/activity_list_for_students";
        break;
      case EntityType.teacher:
        path = apiPath + "/activity_list_for_teacher";
        break;
      case EntityType.room:
        path = apiPath + "/activity_list_for_room";
        break;
    }

    final _request = http.Request("GET", Uri.http(serverAddress, path));
    _request.body = jsonEncode({"id": entityId});
    _request.bodyBytes = utf8.encode(_request.body);

    return this.send(_request);
  }
}

Upvotes: 1

Deepak Senapati
Deepak Senapati

Reputation: 1123

If by body you mean you are trying to append query parameters, then you can try something like this:

var body = {
  'param1': 'one',
  'param2': 'two',
};
var uri =
    Uri.https('www.test.com', '/api/test', body);
var response = await http.get(uri, headers: {
  HttpHeaders.authorizationHeader: 'Token $token',
  HttpHeaders.contentTypeHeader: 'application/json',
});

See here for more info : https://api.dart.dev/stable/2.0.0/dart-core/Uri/Uri.https.html

Upvotes: 1

Jay Kikani
Jay Kikani

Reputation: 149

First you need to add this dependencies in pubspec.yaml

dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  http: ^0.11.3+16

Below is the code snippets for the calling API in flutter.

const baseUrl = "https://jsonplaceholder.typicode.com";

class NetworkApi {
  static Future getUsers() {
    var url = baseUrl + "/users";
    return http.get(url);
  }

  static Future getImages(){
    return http.post('http://xyz.in/api.php',body: {
      "parameter" : "value"
    });
  }
}

Below is the call the API from the dart class.

getImages(){
    NetworkApi.getImages().then((response){
      setState(() {
          print("Response Status");
          print("Response : " + response.body);
          var data = json.decode(response.body);
          var imagesData = data["data"] as List;
//          images = list.map((model) => Data.fromJson(model)).toList();
        images = imagesData.map<Data>((json) => Data.fromJson(json)).toList();
          print("Images : " + images.length.toString());
      });
    });
  }

Upvotes: 2

Related Questions