Search code examples
pythonrestflaskhttpresponseflask-restx

flask REST-API: Wrong value of number in response


I'm using flask-restx for my REST-API. There I noticed a strange behaviour where a large integer value seems to be returned wrong.

I'am using this minimal code snippet to reproduce the issue:

from flask_restx import Resource, Namespace

ns = Namespace('resources')

@ns.route('/<id_>')
@ns.doc(params={"id_": "ID of a resource"})
class ResourceItem(Resource):

@staticmethod
@ns.doc(responses={200: "Success", 404: "Not found"})
def get(id_):
    return 6195659448464973308, 200

The expected content in the response body would be (obviously) 6195659448464973308. But the actual response is 6195659448464973000.

The same happens if the response is a json in the form of:

{"value": 6195659448464973308}

I've tested several large numbers but I always get wrong responses.

What I'am missing or doing wrong here? How could a solution to this problem look?


Solution

  • This is because of how javascript handles large integers. It uses IEEE 754 which the number you're trying to return exceeds it's 53-bit limit precision (i.e - 9007199254740991). I can't think of any elegant solution part of returning it as a string and later handling the conversion on the backend side:

    You can try the following:

    from flask_restx import Resource, Namespace
    
    ns = Namespace('resources')
    
    @ns.route('/<id_>')
    @ns.doc(params={"id_": "Some ID"})
    class ResourceItem(Resource):
    
        @staticmethod
        @ns.doc(responses={200: "Success", 404: "Not found"})
        def get(id_):
            # Here you can return the number as a string
            return {"value": str(6195659448464973308)}, 200