I'm trying to use Sanic-OpenAPI module with sanic to auto-document my own RESTful APIs. So, I installed them by running the following command:
pip install sanic sanic-openapi
# sanic version is 19.12.2
# sanic_openapi version is 0.6.1
And I created this simple project which is, by the way, provided in their official GitHub repository. And it looks like the following:
from sanic import Sanic, response
from sanic_openapi import swagger_blueprint
app = Sanic("app")
app.blueprint(swagger_blueprint)
@app.route("/")
async def test(request):
return response.json({"hello": "world"})
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8000, debug=True)
This runs just fine! But when I try to access the http://localhost:8000/swagger, it throws the following error:
Traceback (most recent call last):
File "/media/anwar/E/Chatbot/NLU_engine/py3.7/lib/python3.7/site-packages/sanic/app.py", line 974, in handle_request
response = handler(request, *args, **kwargs)
File "/media/anwar/E/Chatbot/NLU_engine/py3.7/lib/python3.7/site-packages/sanic_openapi/swagger.py", line 263, in spec
return json(swagger_blueprint._spec)
File "/media/anwar/E/Chatbot/NLU_engine/py3.7/lib/python3.7/site-packages/sanic/response.py", line 234, in json
dumps(body, **kwargs),
TypeError: <sanic_openapi.spec.Spec object at 0x7effe3d2f910> is not JSON serializable
[2020-07-12 11:34:09 +0200] - (sanic.access)[INFO][127.0.0.1:37880]: GET http://localhost:8000/swagger/swagger.json 500 2649
[2020-07-12 11:34:09 +0200] [11014] [ERROR] Exception occurred while handling uri: 'http://localhost:8000/swagger/swagger.json'
Traceback (most recent call last):
File "/media/anwar/E/Chatbot/NLU_engine/py3.7/lib/python3.7/site-packages/sanic/app.py", line 974, in handle_request
response = handler(request, *args, **kwargs)
File "/media/anwar/E/Chatbot/NLU_engine/py3.7/lib/python3.7/site-packages/sanic_openapi/swagger.py", line 263, in spec
return json(swagger_blueprint._spec)
File "/media/anwar/E/Chatbot/NLU_engine/py3.7/lib/python3.7/site-packages/sanic/response.py", line 234, in json
dumps(body, **kwargs),
TypeError: <sanic_openapi.spec.Spec object at 0x7effe3d2f910> is not JSON serializable
After around two hours of searching, I've found out the solution in this issue on their official GitHub repository. The reason, according to the issue, is that sanic-openapi
is not compatible with the last two releases (2.x
and 3.x
) of ujson
.
So, to fix this issue, you need to downgrade your ujson
package to 1.35
like so:
pip install ujson==1.35
And it works perfectly now: