Building Basic RESTful API with Flask-RESTful
Tags: flask, python, flaskrestful, rest
Published: 2018-06-15 18:29:50

---
title: Building Basic RESTful API with Flask-RESTful
published: true
description: In this post, we’ll talk about Building Basic RESTful API with Flask framework.
tags: flask, python, flask-restful, rest
---

![Python Logo](https://thepracticaldev.s3.amazonaws.com/i/308nhtj1smmx0sn1ebui.png)

[This post was first posted on my blog](https://aligoren.com/building-basic-restful-api-with-flask/)

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](https://www.getpostman.com/) or similar software to requests. We’ll use virtualenv to use development environment.  Okay, let’s install the flask-restful library.

```shell
virtualenv .
 
. bin/activate
```

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

```shell
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.

```python
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:

```python
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.

```python
api.add_resource(Quotes, '/')
```

Finally, our codes will like this:

```python
# -*- 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](https://thepracticaldev.s3.amazonaws.com/i/9uttstif5hzgmqcfo75q.png)

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

```json
{
    "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:

```python
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:

```python
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](https://thepracticaldev.s3.amazonaws.com/i/wrhocz6jvjdpwknavbqg.png)

## The PUT Method

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

```python
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:

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

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

![Postman PUT Request](https://thepracticaldev.s3.amazonaws.com/i/0ohbzpqvqgkc50j6itmo.png)

If you want to ask about PUT vs POST you can check this [link](https://restfulapi.net/rest-put-vs-post/). 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](https://flask-restful.readthedocs.io/en/latest/).

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.