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

 

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.

We activated the virtualenv.

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.

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

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.

Finally, our codes will like this:

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

Building Basic RestFul API with Flask

 

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

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:

After that, our post method will like this:

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

Building Basic RestFul API with Flask

 

The PUT Method

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

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

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

Building Basic RestFul API with Flask

 

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.