0

I am building a mobile app with flutter and communicating with a rest API i built with Flask. I am new to the two technologies though. Everything works well when I test with postman but when I test from my flutter app, the request actually processes and logs status code 200 in my Flask app but the response somehow doesn't get returned or is not well formatted as Flutter always shows an error rather saying: XMLHttpRequest error instead of the json response.

Dart code:

final String url = 'http://127.0.0.1:5000/endpoint';
http.Response response = await http.post(url, body: json.encode(body)); 
print(json.decode(response.body));

Flask code:

@app.route('/endpoint', methods=['POST'])
def save_point():
    try:
        body = utils.bytes_to_dict(request.get_data())
        assets = body.get('assets', [])
        if len(assets) < 1:
            raise Exception("'assets' is required")
        
        admin.insert(data = {'selected_assets': assets, 'created_at': utils.gettime()}, id = 'selected_assets')


        return jsonify({ # response is returned here
            'status': True,
            'message': 'Selected assets saved',
            'data': assets
        })
    except Exception as e:
        print('error', e)
        return {
            'status': False,
            'message': str(e)
        }

I already tried adding content-type header to the request in flutter via: await http.post(url, body: json.encode(body), headers: {'Content-type': 'application/json'}); but this causes the request not to get processed in Flask for reasons I do not know.

Please what could be wrong ? Is there a way to get flutter to understand the response ?

davidism
  • 121,510
  • 29
  • 395
  • 339
emmaakachukwu
  • 515
  • 1
  • 7
  • 16

2 Answers2

0

I had to add headers: {"Content-Type": "application/json"} in my post request.

Archit
  • 31
  • 2
0

I think the error is in this line:

body: json.encode(body)

The format of 'body' is already JSON, and this line is encoding it again

blackraven
  • 5,284
  • 7
  • 19
  • 45