Allen Andre Indefenzo
Allen Andre Indefenzo

Reputation: 311

Converting my Postman Call to Dart/Flutter API Call

I hope to use nutritionix api to get food information for the users of my application, I manage to get the call to work in Postman, however I cannot convert it to dart code. I am getting this error: '{message: Unexpected token " in JSON at position 0}'

Here is my (POST) postman call:

Headers for POST call Body for POST call

Here is my attempt at converting that to dart code:

  Future<void> fetchNutritionix() async {
    String url = 'https://trackapi.nutritionix.com/v2/natural/nutrients';
    Map<String, String> headers = {
      "Content-Type": "application/json",
      "x-app-id": "5bf----",
      "x-app-key": "c3c528f3a0c68-------------",
      "x-remote-user-id": "0",
    };
    String query = 'query: chicken noodle soup';

    http.Response response =
        await http.post(url, headers: headers, body: query);

    int statusCode = response.statusCode;
    print('This is the statuscode: $statusCode');
    final responseJson = json.decode(response.body);
    print(responseJson);

    //print('This is the API response: $responseJson');
  }

Any help would be appreciated! And, again thank you!

Upvotes: 1

Views: 7750

Answers (4)

Abdullah Alamodi
Abdullah Alamodi

Reputation: 349

enter image description here

click the three dotes button in request tab and select code option then select your language that you want convert code to

Upvotes: 1

JtheSaw
JtheSaw

Reputation: 149

Also you can now generate Dart code (and many other languages) for your Postman request by clicking the Code button just below the Save button.

Upvotes: 2

Richard Heap
Richard Heap

Reputation: 51751

Your postman screenshot shows x-www-form-urlencoded as the content-type, so why are you changing that to application/json in your headers? Remove the content type header (the package will add it for you) and simply pass a map to the body parameter:

  var response = await http.post(
    url,
    headers: headers,
    body: {
      'query': 'chicken soup',
      'brand': 'acme',
    },
  );

Upvotes: 3

arhak
arhak

Reputation: 2542

review the query you're posting

your Postman input is x-www-form-urlencoded instead of plain text

String query = 'query: chicken noodle soup';

why don't you try JSON better

String query = '{ "query" : "chicken noodle soup" }';

Upvotes: 0

Related Questions