1

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!

4 Answers4

3

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',
    },
  );
Richard Heap
  • 48,344
  • 9
  • 130
  • 112
1

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.

JtheSaw
  • 109
  • 4
1

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

Slava Rozhnev
  • 9,510
  • 6
  • 23
  • 39
0

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" }';
arhak
  • 2,488
  • 1
  • 24
  • 38
  • 1
    Woah! After being stuck at this problem for 2 days you fixed it! Thank you so much! I hope you have a great day/evening! – Allen Andre Indefenzo Nov 07 '19 at 11:13
  • Hello again @arhak, how do I add another body parameter such as "num_servings" : "1"? I tried creating a map but i'm getting an error: 'Unhandled Exception: Bad state: Cannot set the body fields of a Request with content-type "application/json"' – Allen Andre Indefenzo Nov 07 '19 at 13:44
  • @AllenAndreIndefenzo although the `headers` is taking in a map, the `body` is not, so you'd need to make it JSON yourself, e.g. https://stackoverflow.com/a/44740579/1681985 – arhak Nov 08 '19 at 08:12