skip to Main Content

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();
}

Return debug for this commands

Everything works fine with postman.
I hope you could help my with this issue.

2

Answers


  1. Chosen as BEST ANSWER

    It works fine now. I was something wrong on php-service on the header (content-type).

    Thank you for your help Have a nice day.


  2. Pass the map variable directly to be encoded:

    From

    body: json.encode(customBody.toString()),
    

    To

    body: json.encode(customBody),
    

    after that make sure the following:

    • You are using an authorized API Key.
    • You are calling the correct URL, it’s preferable to test it before
      integrating the call within your app.
    • Wait for the results of the call.

    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
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search