Before the application is created, we build a work environment that holds python packages installed apart from other applications.
You install virtualenv in order to build a virtual environment
sudo pip install virtualenv
Then you build and enable a virtual environment called venv
virtualenv venv
source venv/bin/activate
Then Flask & Flast-RESTful are installed into the virtual environment
pip install Flask
pip install flask-restful
Flask Rest API
Now, we have the resting flask library installed. A file called main.py must be created. Initially, you import flask as well as the module flask restful.
from flask import Flask from flask_restful import Resource, Api
app = Flask(__name__) api = Api(app)
We’ll build a small class. It’s code as follows:
classQuotes(Resource): defget(self): return { 'bukowski': { 'quote': ['Some people never go crazy. What truly horrible lives they must lead', 'Can you remember who you were, before the world told you who you should be?' ] }, 'angelou': { 'quote': ['You will face many defeats in life, but never let yourself be defeated'] }
}
I’ve included static data in this case. You could have your own servers, as I said. Then we must add this class to the API library wrapper as a tool.
api.add_resource(Quotes, '/')
The code looks like this:
# -*- coding: utf-8 -*-
from flask import Flask from flask_restful import Resource, Api
app = Flask(__name__) api = Api(app)
classQuotes(Resource): defget(self): return { 'bukowski': { 'quote': ['Some people never go crazy. What truly horrible lives they must lead', 'Can you remember who you were, before the world told you who you should be?' ] }, 'angelou': { 'quote': ['You will face many defeats in life, but never let yourself be defeated'] }
}
api.add_resource(Quotes, '/')
if __name__ == '__main__': app.run(debug=True)
Start the script and it’ll output this:
~ » python api.py * Serving Flask app "case" (lazy loading) * Environment: production WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Debug mode: on * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) * Restarting with stat * Debugger is active! * Debugger PIN: 730-804-219
Open localhost:5000/ and it outputs the complete json object.