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?
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);