Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return bool as POST response using flask [duplicate]

I'm mocking an Post api (written in C#) which return a bool value true or false when called. The content-type is application/json for the request

true

I am now trying to mock that endpoint in Python using Flask and I'm struggling to make it pass a boolean value.

I tried

return make_response(True,200)

or simply

return True

and in both cases the api fails sending the desired response and throws errors.

In a desperate attempt I tried returning "True" as a string

return make_response("True", 200)

That seemed to work at the mock level, but the consuming code (c#) fails as it tries to convert that return value into bool by

result = response.Content.ReadAsAsync<bool>().Result

Any ideas on how to make the mock api return a bool value ???

like image 386
Mateen-Hussain Avatar asked Sep 13 '25 18:09

Mateen-Hussain


2 Answers

You should consider sending json data.

return json.dumps(True)
like image 104
AlokThakur Avatar answered Sep 16 '25 09:09

AlokThakur


You're not returning valid JSON. In JSON the boolean is lowercase, "true". You can use json.dumps to generate the correct JSON serialization of a value. You should also set the content type of the response to application/json. Use app.response_class to build a response.

from flask import json

return app.response_class(json.dumps(True), content_type='application/json')

Typically, you would send more than a single value as the response. Flask provides jsonify as a shortcut to return a JSON object with the keys and values you pass it. (It's been improved in Flask dev version to handle other data besides objects.)

from flask import jsonify

return jsonify(result=True, id=id)
like image 25
davidism Avatar answered Sep 16 '25 09:09

davidism