3

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 ???

Mateen-Hussain
  • 718
  • 1
  • 13
  • 29

2 Answers2

8

You should consider sending json data.

return json.dumps(True)
AlokThakur
  • 3,599
  • 1
  • 19
  • 32
  • You can dump it as json and send it, I have tried it's working. As I know about standard json should be used for communication between REST client and REST server. – AlokThakur Feb 01 '16 at 15:05
  • @DanielF as Davidsm mentions I dont have any control over what data is returned but to mock. I agree it is a bad design to return a boolean as part of Json without any key. – Mateen-Hussain Feb 01 '16 at 15:54
2

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)
davidism
  • 121,510
  • 29
  • 395
  • 339