I'm trying to call an API with a custom Body but I always the same error. Error 400 And the API return "can't json/yaml decode the argument"
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'dart:developer' as developer;
Future\<dynamic\> ApiDiolos() async {
final mapHeader = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-Diolos-Key':
'My-Custom-API-Key'
};
Uri uri = Uri.parse("https://api.diolos.com/myapipage.php");
var customBody = {};
customBody\["action"\] = "6";
customBody\["limit"\] = "null";
customBody\["offset"\] = "0";
final response = await http.post(uri,
headers: mapHeader,
body: json.encode(customBody.toString()),
encoding: Encoding.getByName('utf-8'));
}
void main() {
ApiDiolos();
}
Everything works fine with postman. I hope you could help my with this issue.
Pass the map variable directly to be encoded:
body: json.encode(customBody.toString()),
body: json.encode(customBody),
after that make sure the following:
Look at the following code, and try to refactor it:
Future<Map?> ApiDiolos() async {
final mapHeader = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-Diolos-Key': 'XXXXXXXXXXXXXXXXXXXX' // provide an authorized key
};
Uri uri = Uri.parse(
"https://api.diolos.com/myapipage.php"); // make sure it's a correct URL
var customBody = {"action": "6", "limit": "null", "offset": "0"};
final response =
await http.post(uri, headers: mapHeader, body: json.encode(customBody));
if (response.statusCode == 200) {
return json.decode(response.body);
}
return null;
}
void main() async {
print(await ApiDiolos()); // you must wait for the Future to get completed
}