Sofia E. Sofia E. - 10 months ago 129
JSON Question

REST API on Python for JSON type data

I am currently trying to understand how to create a REST API using Python (Flask) which will allow user to GET a set of data represented in JSON format by browsing the url given as : localhost:5000/DPM. I wrote the following Python script but receive errors as such:


File "sqllite.py", line 23, in
api.add_resource(DPM, '/DPM')
File "C:\Program Files\Anaconda3\lib\site-packages\flask_restful__init__.py", line 404, in add_resource
self._register_view(self.app, resource, *urls, **kwargs)
File "C:\Program Files\Anaconda3\lib\site-packages\flask_restful__init__.py", line 444, in _register_view
resource_func = self.output(resource.as_view(endpoint, *resource_class_args,
AttributeError: type object 'DPM' has no attribute 'as_view'


from flask import Flask
from flask_restful import Resource, Api
from sqlalchemy import create_engine
import json

app = Flask(__name__)
api = Api(app)

class DPM:
def __init__(self, time, month):
self.time = time
self.month = month
ees = DPM('[12.18]','11')

def jdefault(o):
return o.__dict__
print(json.dumps(ees, default=jdefault, indent=4))

api.add_resource(DPM, '/DPM')

if __name__ == '__main__':
app.run(debug=True)


Where did I do wrong here?

Answer Source

The class that you want to expose to your API must inherit from Resource, this class implements basic methods such as the as_view that allows you to render the output. and then you have to implement some method like for example the GET:

from flask import Flask
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)

class DPM(Resource):
    def __init__(self):
       self.time = '[12.18]'
       self.month = "11"
    def get(self):
        return self.__dict__

api.add_resource(DPM, '/DPM')

if __name__ == '__main__':
    app.run(debug=True)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download