Flask Restful

Flask-RESTful is a flask extension used to build REST APIs quickly. Flask-RESTful is a lightweight abstraction that works with existing libraries. It is also helpful for working with minimal setup. To start with Flask-RESTful, you must be familiar with Flask; having flask basics makes you learn Flask-RESTful quickly. This is just another extension of Flask, which is very interesting and helpful in developing API.

In this article, we will learn how to start using Flask-RESTful with Flask.

Installing of Flask-RESTful using the given command

pip install flask-restful

The development version should be downloaded from its page on GitHub. You can use the given commands to download that

git clone https://github.com/flask-restful/flask-restful.git
cd flask-restful
python setup.py develop

By installing this, all dependencies of Flask-RESTful will automatically get installed cause we used pip. Before installing this, we must ensure that the required python version is 2.7 or above.

As we are done with the installation process, now you can work on the minimal API

Minimal Flask-RESTful API

from flask import Flask
from flask_restful import Resource, API
app = Flask(__name__)
api = Api(app)
class HelloWorld(Resource):
    def get(self):
        return {'hello': 'world'}
api.add_resource(HelloWorld, '/')
if __name__ == '__main__':
    app.run(debug=True)    

You must save this code as api.py to run this code using your python interpreter. And as we see in the given code, we enabled Flask Debugging mode, which provides code reloading and error recognition.

$ python api.py 
 *Running on http://127.0.0.1:5000/
*Restarting with reloader

And make sure you are using debug mode in a production environment.

To test your API using curl, you must open a new prompt.

Resourceful Routing

A very important part of Flask-RESTful is its resources. As we saw in the above code, we used “resources”; these are used to give easy access to many HTTP methods by inserting the methods on the resource.

Flask-RESTful uses view methods to understand multiple kinds of return values. Through this, any value can be converted into a new response. This also includes raw flask response objects. You can try setting the response code and response headers using Flask-RESTful using multiple return values as well.

Example

class Todo1(Resource):
    def get(self):
        return {'task': 'Hello world'}
class Todo2(Resource):
    def get(self):
        return {'task': 'Hello world'}, 201
class Todo3(Resource):
    def get(self):
        return {'task': 'Hello world'}, 201, {'tag': 'some-string'}

Output

Flask Restful

A resource might contain multiple URLs, and in Flask-RESTful, you can have multiple URLs to the add_resource() method on the API object, where every URL will be en route to the resource you have in that API. And you can include matching parts of the path as a variable to help.

Parsing Arguments

You can access the requested data easily through Flask using pre-defined commands. But it’s a tough task to check the data, but in Flask-RESTful, there is a built-in process where data validation is easy. You use the following commands to validate the data

from flask_restful import reqparse
parser = reqparse.RequestParser()
parser.add_argument('rate', type=int, help='Rate of this resource is')
args = parser.parse_args()

sometimes using reqparse gives you errors, and this happens when an argument fails to pass validation, flask-restful will give a response by highlighting the error. And the input module gives some built-in common conversion functions like input.date(), inputs.url(), etc.

so calling parse_args with a True command makes sure that an error occurs if the request includes arguments your parser doesn’t have.

Data Formatting

Every field in a return value will be rendered as it is. Using python data structures will work great and might get a bit tough while dealing with other objects. So to solve this problem, flask-restful provides us with a module called fields and marshal_with() decorator. These are similar to WTForm, so you can use the fields module to describe the response structure and make the code simple to understand.

After creating an API, you do modifications to that like

  • can get the list
  • get single task
  • delete a task
  • add a new task
  • update a task, etc

Conclusion:

With this, we covered a quick guide on Flask-RESTful, application of api and some basic concepts. So, the difference between Flask and Flask-RESTful is that Flask is a python framework, and Flask-RESTful is just an extension of Flask, which is used to write a clean oops code for faster API development.