I'm calling a SOAP WebService using Zeep, and it returns a JSON-like response with a datetime
object. I want to write a micro-service using Flask and return proper JSON response. However, Flask complains that:
TypeError: Object of type datetime is not JSON serializable
from flask import Flask
from flask_restful import Resource, Api
import datetime
app = Flask(__name__)
api = Api(app)
class foo(Resource):
def get(self, x):
zeepResponse = {
'Response': {
'Number': x,
'DateTime': datetime.datetime(2020, 1, 1, 0, 0, 0),
'Other': None
}
}
return zeepResponse
api.add_resource(foo, '/post/<int:x>')
if __name__ == '__main__':
app.run(debug=True)
To test from the command line, simply run:
% curl http://localhost:5000/post/911
Would you guide me how to convert zeepResponse
(and the datetime
specifically) to a proper JSON serializable structure?
Calling json.dumps(zeepResponse, default=str)
seems to fix my problem. From Stack Overflow 11875770
from flask import Flask
from flask_restful import Resource, Api
import datetime
import json
app = Flask(__name__)
api = Api(app)
class foo(Resource):
def get(self, x):
zeepResponse = {
'Response': {
'Number': x,
'DateTime': datetime.datetime(2020, 1, 1, 0, 0, 0),
'Other': None
}
}
return json.loads(json.dumps(zeepResponse, default=str))
api.add_resource(foo, '/post/<int:x>')
if __name__ == '__main__':
app.run(debug=True)