Search code examples
pythonpython-3.xsanic

How to return a float (or int) with a sanic API?


I am creating a simple Sanic REST API but cannot figure out how return numeric data. After looking at the docs, it appears that you can only return json, html, text, etc., but no float or int.

I am following the basic example in the docs, except have switched the return to a float:

from sanic import Sanic
from sanic.response import json

app = Sanic()

@app.route("/")
async def test(request):
    return 1.1

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8000)

However, it works perfectly if the return statement is return json({"hello": "world"}). Why can I not return a float? I can return it as return text(1.1), but then does the client who calls it receive it as a str (as opposed to a float)?


Solution

  • Just JSON your number.

    >>> import json
    >>> s = json.dumps(543.34)
    >>> s
    '543.34'
    >>> json.loads(s)
    543.34
    

    With Sanic:

    from sanic import Sanic, response
    from sanic.response import json
    
    app = Sanic()
    
    @app.route("/")
    async def test(request):
        return response.json(1.1)
    
    if __name__ == "__main__":
        app.run(host="0.0.0.0", port=8000)