0

I have a json api. Like this 'https://myapiurl.com/api.json'. I can read data in this api and I can fetch data in my app. But i can't post data in the my api. Here my source code.

I am fetching data this way.

Future<List<Stock>> getStock() async {
    var response = await http.get(Uri.parse("https://myapiurl.com/api.json"));
    var _stocks = <Stock>[];
    _stocks = (json.decode(utf8.decode(response.bodyBytes)) as List)
        .map((singleStockMap) => Stock.fromJson(singleStockMap))
        .toList();
    return _stocks;
  }

And i am trying this way for post data.

postData() async {
    try {
      var response = await http
          .post(Uri.parse("https://myapiurl.com/api.json"), body: {
        "productName": 1.toString(),
        "productStock": "Hello",
      });
      print(response.body);
    } catch (e) {
      print(e);
    }
  }

What is wrong?

  • refer my answer [here](https://stackoverflow.com/a/68767696/13997210) hope its help to you – Ravindra S. Patil Nov 02 '21 at 10:05
  • It returns successfully. But still it is not writing the data to my api file. Why could that be? –  Nov 02 '21 at 10:12
  • are you print your data to console and check statuscode also – Ravindra S. Patil Nov 02 '21 at 10:14
  • Yes I did it. No problem here but it is not writing the data to my api file. –  Nov 02 '21 at 10:17
  • can you tell me your api url is hosted I will check on my machine. and give me the column name also – Ravindra S. Patil Nov 02 '21 at 10:19
  • And i am developing for flutter desktop. Maybe thats important info. –  Nov 02 '21 at 10:28
  • can you tell me which method do you have for this API get or post I tried this url it gives me the data but not statuscode – Ravindra S. Patil Nov 02 '21 at 10:29
  • What means which method sir? And i can access status code with your answer. Status code 200 in debug console. –  Nov 02 '21 at 10:31
  • hey bro I have try your URL it gives the 200 status code but data is not inserted , I also try this Postman also but not work I think this url is made by GET method not POST method try to make it POST method – Ravindra S. Patil Nov 02 '21 at 10:58
  • Sorry i will try another way for data situations. Maybe i can use PhpMyAdmin or Firebase. I was try API because I think this so basic but thats not seems simple –  Nov 02 '21 at 20:17

1 Answers1

0

you have to encode your body before passing it:

passBody = json.encode(body);

Reham Alraee
  • 139
  • 8