Isuru Bandara
Isuru Bandara

Reputation: 360

How to use API using http package in flutter

Im trying to use an API to remove background of an image. Therefore, I am using http flutter package. But I am getting <title>400 Bad Request</title> error. How can I fix this?

This is what i tried,

  removeBackGround(String imagePath) async {
    
    final body = {"image_file": imagePath};
    final headers = {"X-API-Key": "e5adebcdc77**************"};
    final response = await http.post(Uri.parse("https://sdk.photoroom.com/v1/segment"),
        body: body,
        headers: headers);

    if (response.statusCode == 200) {
      print("response  ok");
      
    } else {
      throw Exception('Failed to do network requests: Error Code: ${response.statusCode}\nBody: ${response.body}');
    }
  }

this is the error

E/flutter (14230): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: Exception: Failed to do network requests: Error Code: 400
E/flutter (14230): Body: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
E/flutter (14230): <title>400 Bad Request</title>
E/flutter (14230): <h1>Bad Request</h1>
E/flutter (14230): <p>Could not decode image, ensure image_file or image_file_b64 is set</p>

Upvotes: 0

Views: 329

Answers (1)

Mehran Ullah
Mehran Ullah

Reputation: 792

You can use the post method slightly in a different way, by using MulipartFormRequest

Future removeBackGround(imagePath) async {
  var request = http.MultipartRequest(
      'POST', Uri.parse("https://sdk.photoroom.com/v1/segment"));
  await http.MultipartFile.fromPath(
    'image',
    imagePath,
    filename: 'image_$name.jpg',
  );
  // request.fields['companyName'] = name;
  // request.fields['own_id'] = id;
  request.headers["X-API-Key"] = "e5adebcdc77**************";

  var res = await request.send();
  return res.statusCode;
}

Using this method you can upload an images and json data at once.

Upvotes: 1

Related Questions