1

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 "mysql.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
energy = DPM('[12.18]','11')

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

api.add_resource(DPM, '/DPM')

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

Where did I do wrong here?

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

4 Comments

Great. It works. But shouldn't I import pluggable class-based views to actually utilise the as__view methods? and could you please explain to me in brief why I don't need to use import json to serialize the data into JSON?
the idea of an API is not to have to write functions or methods already known, in this case Resource implements inherits from class-based views, and implements, exposing the json. that is, this class expects you to implement the get, post, delete, put methods that will be called when you use the verbs GET, POST, DELETE, PUT. In conclusion, the API makes life easier for us, we just have to implement those methods and return a dictionary of the data we want to expose.
Hi @eyllanesc. Say if I'm testing this on a CentOS server running on localhost on an intranet network (with IP of maybe 10.210.1.99 ), do you know how can I allow other computers in the same network to send the same request? I tried browsing for 10.210.1.99:5000 or 10.210.1.99:5000/DPM but failed. But when I pinged from my PC 10.210.1.99, I received response.
Hi guys. Thank you for your help. I have figured out on how to expose the REST API on CentOS server running on intranet / corporate network. Firstly, do lsof -Pnl +M -i4 and kill any program on port 5000. Then add app.run(host='0.0.0.0') before app.run(debug=True) line. Lastly, go to any other computer within the network and type the IP address. For the above case example : 10.210.1.99:5000.
0

I am assuming you are installed required packages(flask_restful,jsonify,)

class DPM(Resource):
    def get(self):
        cur = mysql.connection.cursor()
        result = cur.execute('your sql command here')
        list= cur.fetchall()
        mysql.connection.commit()
        cur.close()
        rest_list = jsonify(list)
        return  rest_list

api.add_resource(DPM, '/dpm')

if name == '__main__':
    app.run()

This is for mysql without orm with flask_restful

You can find full http methods on flask rest here

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.