DEV Community

Itachi Uchiha
Itachi Uchiha

Posted on

Building Basic RESTful API with Flask-RESTful

Python Logo

This post was first posted on my blog

Hi. In this post, I’ll talk about Building Basic RESTful API with Flask framework. Before we start we’ll install the Flask RESTful library. In this example will not use any database. But you can use your own. I’ll just show how to create Rest API with Flask.

Building Basic RestFul API with Flask

We might need to Postman or similar software to requests. We’ll use virtualenv to use development environment. Okay, let’s install the flask-restful library.

virtualenv .

. bin/activate

We activated the virtualenv. Let's install the flask-restful library.

pip install flask-restful

Now, we installed the flask-restful library. We need to create a file named main.py. Its name can be anything. We will firstly import flask and its flask_restful library.

from flask import Flask
from flask_restful import Resource, Api

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

After that, we will create a simple class. It will like this:

class Quotes(Resource):
    def get(self):
        return {
            'ataturk': {
                'quote': ['Yurtta sulh, cihanda sulh.', 
                    'Egemenlik verilmez, alınır.', 
                    'Hayatta en hakiki mürşit ilimdir.']
            },
            'linus': {
                'quote': ['Talk is cheap. Show me the code.']
            }

        }

In this example, we used static data. As I said you can use your own database. Now we need to add this class as a resource to API library wrapper.

api.add_resource(Quotes, '/')

Finally, our codes will like this:

# -*- coding: utf-8 -*-

from flask import Flask
from flask_restful import Resource, Api

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

class Quotes(Resource):
    def get(self):
        return {
            'ataturk': {
                'quote': ['Yurtta sulh, cihanda sulh.', 
                    'Egemenlik verilmez, alınır.', 
                    'Hayatta en hakiki mürşit ilimdir.']
            },
            'linus': {
                'quote': ['Talk is cheap. Show me the code.']
            }

        }


api.add_resource(Quotes, '/')

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

Above code, we created a method named get for HTTP Get requests. We tried with the postman

Postman Get Request

When you try unimplemented HTTP requests you will see a warning message like this:

{
    "message": "The method is not allowed for the requested URL."
}

The POST Method

For example, you want to work with post requests for this class. You must create a method named post. Let’s create our post method to HTTP Post requests. Firstly, we need to import reqparse. So, our import statements will change like below:

from flask import Flask
from flask_restful import Resource, Api, reqparse

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

parser = reqparse.RequestParser()

After that, our post method will like this:

def post(self):
        parser.add_argument('quote', type=str)
        args = parser.parse_args()

        return {
            'status': True,
            'quote': '{} added. Good'.format(args['quote'])
        }

Let’s try a simple HTTP Post request with the Postman:

Postman POST Request

The PUT Method

Let’s create one PUT method to update the resource. Our put method will like this:

def put(self, id):
        parser.add_argument('quote', type=str)
        args = parser.parse_args()

        return {
            'id': id,
            'status': True,
            'quote': 'The quote numbered {} was updated.'.format(id)
        }

After that, we need to change our resource like this:

api.add_resource(Quotes, '/', '/update/<int:id>')

We’ve created an HTTP Put request thanks to the Postman.

Postman PUT Request

If you want to ask about PUT vs POST you can check this link. We could create a DELETE method. In this post, I’ll not create and HTTP Delete method. You can access more detail about Flask-RESTful thanks to this link.

In this post, we talked about Building Basic RestFul API with Flask. I hope this post, will help you to design great RESTful API.

Thank you for reading.

Top comments (2)

Collapse
 
evanwaltersdev profile image
Evan Walters

Awesome. Have you checked out flask-restplus? It's a fork of flask-restful with loads of added features.

Collapse
 
abdurrahmaanj profile image
Abdur-Rahmaan Janhangeer

ever tried marshmallow?