Building RESTful APIs With Flask: The DIY Approach

REST (REpresentational State Transfer) is a web development architecture design style that refers to logically separating your API resources to enable easy access, manipulation, and scaling. Reusable components are written to be easily managed via simple and intuitive HTTP requests, which can be GET, POST, PUT, PATCH, and DELETE (there can be more, but above are the most commonly used ones).

Despite what it looks like, REST does not command a protocol or a standard. It just sets a software architectural style for writing web applications and APIs and simplifies the interfaces within and outside the application. Web service APIs that are written to follow the REST principles are called RESTful APIs.

In this three-part tutorial series, I will cover how RESTful APIs can be created using Flask as a web framework. The first part will cover how to create class-based REST APIs in a DIY way (do it yourself)—implementing them all by yourself without using any third-party extensions. In the latter parts of this series, I will cover how to leverage various Flask extensions to build more effective REST APIs more easily.

Getting Started

Lets start by creating a project directory and a virtual environment

Installing Dependencies

The following packages need to installed for the application that we’ll be developing.

The above commands should install all the required packages that are needed for this application to work.

The Flask Application

For this tutorial, we will create a small application to create a trivial model for Product. Then demonstrate how we can write a RESTful API for the same. Below is the structure of the application.

We won’t be creating a front-end for this application as RESTful APIs endpoints can be tested directly by making HTTP calls using various other methods. Open my_app/__int__.py and add the following code.

We first initialize a Flask app instance in the code above, configure it with an SQlite database, and finally create the database. db.create_all() will create a new database at the location provided against SQLALCHEMY_DATABASE_URI if a database does not already exist at that location; otherwise, it loads the application with the same database. We won’t be creating a front-end for this application as RESTful APIs endpoints can be tested directly by making HTTP calls using various other methods.

Open product/models.py and add the models for our product. The model will have 3 fields, namely.

  • id: a unique primary key
  • name
  • price

In the file above, we have created a very trivial model for storing the name and price of a Product. This will create a table in SQLite corresponding to the details provided in the model.

Flask Blueprint

Flask blueprint help to create structure in Flask application by grouping views templates e.t.c into reusable components. Open product/views.py and create a Flask Blueprint that contains the home view and then use it in the application.

To use the blueprint, you have to register it in the application using the register_blueprint() command. Open my_app/__init__.py 

Views

Open product.views.py and create our views. We will use pluggable class-based views  which provide flexibility. 

The major crux of this tutorial is dealt with in the file above. Flask provides a utility called pluggable views, which allows you to create views in the form of classes instead of normally as functions. Method-based dispatching (MethodView) is an implementation of pluggable views which allows you to write methods corresponding to the HTTP methods in lower case. In the example above, I have written methods get() and post() corresponding to HTTP’s GET and POST respectively.

Here we create a ProductView class that defines a get and post function. The get function retrieves the products from the database and paginates the results. 

The post method obtains request data in json format and adds the data to the database.

Routing

Routing is also implemented in a different manner. After adding the views, add the routes.

In the code above, we can specify the methods that will be supported by any particular rule. Any other HTTP call would be met by Error 405 Method not allowed.

Running the Application

To run the application, execute the script run.py. The contents of this script are:

Now just execute from the command line:

To check if the application works, fire up http://127.0.0.1:5000/ in your browser, and a simple screen with a welcome message should greet you.

Testing the RESTful API

To test this API, we can simply make HTTP calls using any of the many available methods. GET calls can be made directly via the browser. POST calls can be made using a Chrome extension like Postman or from the command line using curl, or we can use Python’s requests library to do the job for us. I’ll use the requests library here for demonstration purposes.  Start by installing the request library using pip

Let’s make a GET call first to assure that we don’t have any products created yet. As per RESTful API’s design, a get call which looks something like /product/ should list all products. Then I will create a couple of products by making POST calls to /product/ with some data. Then a GET call to /product/ should list all the products created. To fetch a specific product, a GET call to /product/<product id> should do the job.

Enter the python interactive shell

 Below is a sample of all the calls that can be made using this example.

Conclusion

In this tutorial, you saw how to create RESTful interfaces all by yourself using Flask’s pluggable views utility. This is the most flexible approach while writing REST APIs but involves much more code to be written. 

There are extensions that simplify life and automate the implementation of RESTful APIs to a huge extent. We will be covering these in the next couple of parts of this tutorial series.

This post has been updated with contributions from Esther Vaati. Esther is a software developer and writer for Envato Tuts+.

REST (REpresentational State Transfer) is a web development architecture design style that refers to logically separating your API resources to enable easy access, manipulation, and scaling. Reusable components are written to be easily managed via simple and intuitive HTTP requests, which can be GET, POST, PUT, PATCH, and DELETE (there can be more, but above are the most commonly used ones).

Despite what it looks like, REST does not command a protocol or a standard. It just sets a software architectural style for writing web applications and APIs and simplifies the interfaces within and outside the application. Web service APIs that are written to follow the REST principles are called RESTful APIs.

In this three-part tutorial series, I will cover how RESTful APIs can be created using Flask as a web framework. The first part will cover how to create class-based REST APIs in a DIY way (do it yourself)—implementing them all by yourself without using any third-party extensions. In the latter parts of this series, I will cover how to leverage various Flask extensions to build more effective REST APIs more easily.

Getting Started

Lets start by creating a project directory and a virtual environment

Installing Dependencies

The following packages need to installed for the application that we’ll be developing.

The above commands should install all the required packages that are needed for this application to work.

The Flask Application

For this tutorial, we will create a small application to create a trivial model for Product. Then demonstrate how we can write a RESTful API for the same. Below is the structure of the application.

We won’t be creating a front-end for this application as RESTful APIs endpoints can be tested directly by making HTTP calls using various other methods. Open my_app/__int__.py and add the following code.

We first initialize a Flask app instance in the code above, configure it with an SQlite database, and finally create the database. db.create_all() will create a new database at the location provided against SQLALCHEMY_DATABASE_URI if a database does not already exist at that location; otherwise, it loads the application with the same database. We won’t be creating a front-end for this application as RESTful APIs endpoints can be tested directly by making HTTP calls using various other methods.

Open product/models.py and add the models for our product. The model will have 3 fields, namely.

  • id: a unique primary key
  • name
  • price

In the file above, we have created a very trivial model for storing the name and price of a Product. This will create a table in SQLite corresponding to the details provided in the model.

Flask Blueprint

Flask blueprint help to create structure in Flask application by grouping views templates e.t.c into reusable components. Open product/views.py and create a Flask Blueprint that contains the home view and then use it in the application.

To use the blueprint, you have to register it in the application using the register_blueprint() command. Open my_app/__init__.py 

Views

Open product.views.py and create our views. We will use pluggable class-based views  which provide flexibility. 

The major crux of this tutorial is dealt with in the file above. Flask provides a utility called pluggable views, which allows you to create views in the form of classes instead of normally as functions. Method-based dispatching (MethodView) is an implementation of pluggable views which allows you to write methods corresponding to the HTTP methods in lower case. In the example above, I have written methods get() and post() corresponding to HTTP’s GET and POST respectively.

Here we create a ProductView class that defines a get and post function. The get function retrieves the products from the database and paginates the results. 

The post method obtains request data in json format and adds the data to the database.

Routing

Routing is also implemented in a different manner. After adding the views, add the routes.

In the code above, we can specify the methods that will be supported by any particular rule. Any other HTTP call would be met by Error 405 Method not allowed.

Running the Application

To run the application, execute the script run.py. The contents of this script are:

Now just execute from the command line:

To check if the application works, fire up http://127.0.0.1:5000/ in your browser, and a simple screen with a welcome message should greet you.

Testing the RESTful API

To test this API, we can simply make HTTP calls using any of the many available methods. GET calls can be made directly via the browser. POST calls can be made using a Chrome extension like Postman or from the command line using curl, or we can use Python’s requests library to do the job for us. I’ll use the requests library here for demonstration purposes.  Start by installing the request library using pip

Let’s make a GET call first to assure that we don’t have any products created yet. As per RESTful API’s design, a get call which looks something like /product/ should list all products. Then I will create a couple of products by making POST calls to /product/ with some data. Then a GET call to /product/ should list all the products created. To fetch a specific product, a GET call to /product/<product id> should do the job.

Enter the python interactive shell

 Below is a sample of all the calls that can be made using this example.

Conclusion

In this tutorial, you saw how to create RESTful interfaces all by yourself using Flask’s pluggable views utility. This is the most flexible approach while writing REST APIs but involves much more code to be written. 

There are extensions that simplify life and automate the implementation of RESTful APIs to a huge extent. We will be covering these in the next couple of parts of this tutorial series.

This post has been updated with contributions from Esther Vaati. Esther is a software developer and writer for Envato Tuts+.


Print Share Comment Cite Upload Translate
APA
Shalabh Aggarwal | Sciencx (2024-03-29T05:57:00+00:00) » Building RESTful APIs With Flask: The DIY Approach. Retrieved from https://www.scien.cx/2016/05/30/building-restful-apis-with-flask-the-diy-approach/.
MLA
" » Building RESTful APIs With Flask: The DIY Approach." Shalabh Aggarwal | Sciencx - Monday May 30, 2016, https://www.scien.cx/2016/05/30/building-restful-apis-with-flask-the-diy-approach/
HARVARD
Shalabh Aggarwal | Sciencx Monday May 30, 2016 » Building RESTful APIs With Flask: The DIY Approach., viewed 2024-03-29T05:57:00+00:00,<https://www.scien.cx/2016/05/30/building-restful-apis-with-flask-the-diy-approach/>
VANCOUVER
Shalabh Aggarwal | Sciencx - » Building RESTful APIs With Flask: The DIY Approach. [Internet]. [Accessed 2024-03-29T05:57:00+00:00]. Available from: https://www.scien.cx/2016/05/30/building-restful-apis-with-flask-the-diy-approach/
CHICAGO
" » Building RESTful APIs With Flask: The DIY Approach." Shalabh Aggarwal | Sciencx - Accessed 2024-03-29T05:57:00+00:00. https://www.scien.cx/2016/05/30/building-restful-apis-with-flask-the-diy-approach/
IEEE
" » Building RESTful APIs With Flask: The DIY Approach." Shalabh Aggarwal | Sciencx [Online]. Available: https://www.scien.cx/2016/05/30/building-restful-apis-with-flask-the-diy-approach/. [Accessed: 2024-03-29T05:57:00+00:00]
rf:citation
» Building RESTful APIs With Flask: The DIY Approach | Shalabh Aggarwal | Sciencx | https://www.scien.cx/2016/05/30/building-restful-apis-with-flask-the-diy-approach/ | 2024-03-29T05:57:00+00:00
https://github.com/addpipe/simple-recorderjs-demo