How do you add query parameters to a Dart http request?
If you dont want to override the scheme of base endpoint url, use the below technique to convert the map to query string and append it to the base endpoint url
var endpointUrl = 'https://www.myurl.com/api/v1/user';
Map<String, String> queryParams = {
'param1': '1',
'param2': '2'
};
var headers = {
HttpHeaders.authorizationHeader: 'Token $token',
HttpHeaders.contentTypeHeader: 'application/json',
}
String queryString = Uri.parse(queryParameters: queryParams).query;
var requestUrl = endpointUrl + '?' + queryString; // result - https://www.myurl.com/api/v1/user?param1=1¶m2=2
var response = await http.get(requestUrl, headers: headers);
You'll want to construct a Uri
and use that for the request. Something like
final queryParameters = {
'param1': 'one',
'param2': 'two',
};
final uri =
Uri.https('www.myurl.com', '/api/v1/test/${widget.pk}', queryParameters);
final response = await http.get(uri, headers: {
HttpHeaders.authorizationHeader: 'Token $token',
HttpHeaders.contentTypeHeader: 'application/json',
});
See https://api.dartlang.org/stable/2.0.0/dart-core/Uri/Uri.https.html
this is more simple
final uri = Uri.parse('$baseUrl/v1/endpoint').replace(queryParameters: {
'page': page,
'itemsPerPage': itemsPerPage,
});
final response = await client.get(uri);