Is it possible to make a GET request with a body in Flutter?

8,658

You can use the Request class for this:

final request = Request('GET', 'http://example.com/api/v1');

request.body = '{"id": 1}';

final response = request.send().stream.first;

Alternatively, you can also use idiomatic syntax, i.e. standard procedure, and provide your parameter in the URI:

await get('http://example.com/api/v1?id=1', headers: headers, body: json);
Share:
8,658
UndercoverCoder
Author by

UndercoverCoder

Updated on December 13, 2022

Comments

  • UndercoverCoder
    UndercoverCoder over 1 year

    I made an API that reads data from a database based on a given id via a GET request.

    It gets some data where id equals some integer.

    I want to call this API in Flutter using package:http/http.dart but the GET request doesn't allow me to enter a request body (where I would pass in the id).

    I've Googled and Googled to no avail (I may just be googling the wrong thing). I tried changing my API to a POST rather than GET, which works, but I feel it defeats the purpose of GET.

    Here is how I do it using POST:

    String url = "http://example.com/api/v1";
    Map<String, String> headers = {"Content-type": "application/json"};
    
    String json = '{"id": 1}';
    
    Response response = await post(url, headers: headers, body: json);
    

    But can I achieve this with GET in Flutter?

  • UndercoverCoder
    UndercoverCoder over 4 years
    Thank you so much!! Works like a charm :)
  • Ephenodrom
    Ephenodrom over 4 years
    It is definitely not a standard to send a body via a GET request! That's how we get totally crazy APIs out there, that are a pain in the ass to implement.
  • Ephenodrom
    Ephenodrom over 4 years
    Check out tools.ietf.org/html/rfc2616#section-9.3 : "The GET method means retrieve whatever information (in the form of an entity) is identified by the Request-URI."
  • harm
    harm about 4 years
    RFC2616 has been deprecated. RFCs 7230 to 7237 is the new hipness. The point, however, still stands.
  • s.j
    s.j over 3 years
    @creativecreatorormaybenot Future<EmployeeIfscDetail> getEmployeeIfscDetail(BuildContext context,String ifsc,String token) async { var _response = await _employeeModel.getEmployeeIfscDetail(jsonEncode(<String, dynamic>{APIKey.IFSC: ifsc}),token); .. } trying to fetch data like this but its giving error all time - Unhandled Exception: NoSuchMethodError: The method '[]' was called on null. Receiver: null Tried calling: []("BankName")
  • creativecreatorormaybenot
    creativecreatorormaybenot over 3 years
    @Ephenodrom I agree, but I wanted to answer the question nonetheless. It is also why I included the idiomatic approach.