Search code examples
flutterpostmanhttp-post

Post Api request Flutter


I have to make a Post Api Request using Flutter. The Postman screenshot is attached for reference. can someone help me with the code [1]: https://i.sstatic.net/VQ23OMth.png

Here is the code sample that I have tried

class ProfileRemoteDatasourceImpl implements ProfileRemoteDatasource {
  @override
  Future<SaveBuyerModel> saveBuyerInfo(
    {required File image, required BuyerModel buyerModel}) async {
      try {
        final body = {"File": image, "buyerModel": buyerModel};
        const endpoint = '${MyAppConstants.baseUrl}/v1/save/buyer';
        var myurl = Uri.parse(endpoint);
        final response = await http.post(myurl,
            headers: {
              'Content-Type': 'application/json',
            },
            body: body);
  
        Map<String, dynamic> data1 = json.decode(response.body)["data"];
  
        return SaveBuyerModel.fromMap(data1);
      } on ServerException catch (e) {
        throw ServerException(e.message);
      } catch (e) {
        throw TimeoutException(e.toString());
      }
  }
}

Solution

  • According to your screenshot:

    • The content type must be multipart/form-data
    • The BuyerModel need to be a file containing a json.
    • You need to send files and not a raw body.

    So your request will look like:

    var bytes = await image.readAsBytes();
    var request = http.MultipartRequest('POST', uri)
      ..headers.addAll({'Content-Type': 'multipart/form-data'})
      ..files.add(await http.MultipartFile.fromBytes('File', bytes))
      ..files.add(await http.MultipartFile.fromString(
         'buyerModel', 
         buyerModel.toJson(), 
         filename: 'input.json',
         contentType: MediaType('application', 'json')
      )
    );
    var streamedResponse = await request.send();
    var response = await http.Response.fromStream(streamedResponse);
    return SaveBuyerModel.fromMap(jsonDecode(response.body)["data"]);