0

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?

h q
  • 1,168
  • 2
  • 10
  • 23
  • JSON doesn't have a datetime type... – thebjorn Jan 26 '20 at 09:11
  • @thebjorn Ok. Zeep returns JSON-like structure, then. How can I convert it to proper JSON? Thanks! – h q Jan 26 '20 at 11:15
  • There is no such thing as a "JSON-like structure", something is either JSON data (i.e. an utf-8 encoded string) or data that is JSON serializable by a particular json serializer. The serializer you're using, at least in the configuration that you are using it in, does not consider datetimes json serializable (because, again, datetime is not one of the types defined in the JSON definition). How _you_ want to serialize datetimes all depends on how you design your api. ISO 8601 formatted UTC is always a good choice, maybe try that..? – thebjorn Jan 26 '20 at 13:30

1 Answers1

2

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)
h q
  • 1,168
  • 2
  • 10
  • 23