Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make an http DELETE request with JSON body in Flutter?

In flutter project, I want to perform a DELETE request with JSON body. But whenever I am trying to use http.delete method it is showing me - The named parameter 'body' isn't defined.

Here's the example of my API delete request-

url: 'BASE_URL'+notes/delete;

Header:

Content-Type : 'application/json',

token: 'my token',

jwt: ' my jwt'

Body:

{

        "id":"4"

}

Response:

status: "Deleted"

So, I need to make the regarding DELETE request with the following body and headers mentioned above and from the JSON response I need to save the value of status in a String. Here, I need a help with the code to make this delete request.

Please inform the entire procedure to make the DELETE request and getting response in the above mentioned way.

like image 980
S. M. Asif Avatar asked Dec 13 '22 11:12

S. M. Asif


1 Answers

You can use Request from http package:

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

Future<String> deleteWithBodyExample() async {
  final baseUrl = "baseUrl";
  final url = Uri.parse(baseUrl + "notes/delete");
  final request = http.Request("DELETE", url);
  request.headers.addAll(<String, String>{
    "Accept": "application/json",
    "token": "my token",
    "jwt" : "my jwt"
  });
  request.body = jsonEncode({"id": 4});
  final response = await request.send();
  if (response.statusCode != 200)
    return Future.error("error: status code ${response.statusCode}");
  return await response.stream.bytesToString();
}
like image 174
Roi Snir Avatar answered Dec 18 '22 12:12

Roi Snir