Building RESTful APIs With Flask: An ORM With SQLAlchemy

In the first part of this three-part tutorial series, we saw how to write RESTful APIs using Flask as the web framework. The previous approach provided a lot of flexibility but involved writing a lot of code that otherwise could have been avoided in more generic cases. 

In this part, we will use a Flask extension, Flask-Restless, which simply generates RESTful APIs for database models defined with SQLAlchemy. I will take the same sample application as in the previous part to maintain context and continuity. The full source code for the previous project can be found in our GitHub repo.

Installing Dependencies

While continuing with the application from the first part, we need to install only one dependency:

The Application

Flask-Restless makes adding RESTful API interfaces to models written with SQLAlchemy a piece of cake.  First, add the REST APIManager from the flask.ext.restless extension to the application configuration file. 

Add the following lines to the flask_app/my_app/__init__.py file:

Just adding the above couple of lines to the existing code should suffice. In the code above, we create the Flask-Restless API manager.

flask_app/my_app/product/views.py

This file comprises the bulk of the changes from the previous part. Below is the complete rewritten file.

It is pretty self-explanatory how the above code would work. We just imported the manager created in a previous file, and it is used to create an API for the Product model with the listed methods. We can add more methods like DELETE, PUT, and PATCH.

We don’t need to create any views since Flask Restless will automatically generate them. The API endpoints specified above will be available at /api/<tablename> by default.  

The API in Action

Let’s test this application by creating some products and listing them. The endpoint created by this extension by default is http://localhost:5000/api/product.

As I did in the last part of this tutorial series, I will test this using the requests library via terminal.

Here is how to add products using Postman:

How to Customize the API

It is convenient to have the RESTful APIs created automatically, but each application has some business logic that calls for customizations, validations, and clever/secure handling of requests. 

Here, request preprocessors and postprocessors come to the rescue. As the names signify, methods designated as preprocessors run before processing the request, and methods designated as postprocessors run after processing the request. create_api() is the place where they are defined as dictionaries of the request type (eg. GET or POST) and the methods as list which will act as preprocessors or postprocessors on the specified request.

Below is a template example:

The GET, PUT, and PATCH methods have the flexibility of being fired for single as well as multiple records; therefore, they have two types each. In the code above, notice 'GET_SINGLE' and 'GET_MANY' for GET requests. 

The preprocessors and postprocessors accept different parameters for each type of request and work without any return value. This is left for you to try on your own.

Conclusion

In this part of this tutorial series, we saw how to create a RESTful API using Flask by adding a couple of lines to an SQLAlchemy-based model. 

In the next and last part of this series, I will cover how to create a RESTful API using another popular Flask extension, but this time, the API will be independent of the modeling tool used for the database.

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


This content originally appeared on Envato Tuts+ Tutorials and was authored by Shalabh Aggarwal

In the first part of this three-part tutorial series, we saw how to write RESTful APIs using Flask as the web framework. The previous approach provided a lot of flexibility but involved writing a lot of code that otherwise could have been avoided in more generic cases. 

In this part, we will use a Flask extension, Flask-Restless, which simply generates RESTful APIs for database models defined with SQLAlchemy. I will take the same sample application as in the previous part to maintain context and continuity. The full source code for the previous project can be found in our GitHub repo.

Installing Dependencies

While continuing with the application from the first part, we need to install only one dependency:

The Application

Flask-Restless makes adding RESTful API interfaces to models written with SQLAlchemy a piece of cake.  First, add the REST APIManager from the flask.ext.restless extension to the application configuration file. 

Add the following lines to the flask_app/my_app/__init__.py file:

Just adding the above couple of lines to the existing code should suffice. In the code above, we create the Flask-Restless API manager.

flask_app/my_app/product/views.py

This file comprises the bulk of the changes from the previous part. Below is the complete rewritten file.

It is pretty self-explanatory how the above code would work. We just imported the manager created in a previous file, and it is used to create an API for the Product model with the listed methods. We can add more methods like DELETE, PUT, and PATCH.

We don't need to create any views since Flask Restless will automatically generate them. The API endpoints specified above will be available at /api/<tablename> by default.  

The API in Action

Let's test this application by creating some products and listing them. The endpoint created by this extension by default is http://localhost:5000/api/product.

As I did in the last part of this tutorial series, I will test this using the requests library via terminal.

Here is how to add products using Postman:

How to Customize the API

It is convenient to have the RESTful APIs created automatically, but each application has some business logic that calls for customizations, validations, and clever/secure handling of requests. 

Here, request preprocessors and postprocessors come to the rescue. As the names signify, methods designated as preprocessors run before processing the request, and methods designated as postprocessors run after processing the request. create_api() is the place where they are defined as dictionaries of the request type (eg. GET or POST) and the methods as list which will act as preprocessors or postprocessors on the specified request.

Below is a template example:

The GET, PUT, and PATCH methods have the flexibility of being fired for single as well as multiple records; therefore, they have two types each. In the code above, notice 'GET_SINGLE' and 'GET_MANY' for GET requests. 

The preprocessors and postprocessors accept different parameters for each type of request and work without any return value. This is left for you to try on your own.

Conclusion

In this part of this tutorial series, we saw how to create a RESTful API using Flask by adding a couple of lines to an SQLAlchemy-based model. 

In the next and last part of this series, I will cover how to create a RESTful API using another popular Flask extension, but this time, the API will be independent of the modeling tool used for the database.

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


This content originally appeared on Envato Tuts+ Tutorials and was authored by Shalabh Aggarwal


Print Share Comment Cite Upload Translate Updates
APA

Shalabh Aggarwal | Sciencx (2016-06-14T06:43:45+00:00) Building RESTful APIs With Flask: An ORM With SQLAlchemy. Retrieved from https://www.scien.cx/2016/06/14/building-restful-apis-with-flask-an-orm-with-sqlalchemy/

MLA
" » Building RESTful APIs With Flask: An ORM With SQLAlchemy." Shalabh Aggarwal | Sciencx - Tuesday June 14, 2016, https://www.scien.cx/2016/06/14/building-restful-apis-with-flask-an-orm-with-sqlalchemy/
HARVARD
Shalabh Aggarwal | Sciencx Tuesday June 14, 2016 » Building RESTful APIs With Flask: An ORM With SQLAlchemy., viewed ,<https://www.scien.cx/2016/06/14/building-restful-apis-with-flask-an-orm-with-sqlalchemy/>
VANCOUVER
Shalabh Aggarwal | Sciencx - » Building RESTful APIs With Flask: An ORM With SQLAlchemy. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2016/06/14/building-restful-apis-with-flask-an-orm-with-sqlalchemy/
CHICAGO
" » Building RESTful APIs With Flask: An ORM With SQLAlchemy." Shalabh Aggarwal | Sciencx - Accessed . https://www.scien.cx/2016/06/14/building-restful-apis-with-flask-an-orm-with-sqlalchemy/
IEEE
" » Building RESTful APIs With Flask: An ORM With SQLAlchemy." Shalabh Aggarwal | Sciencx [Online]. Available: https://www.scien.cx/2016/06/14/building-restful-apis-with-flask-an-orm-with-sqlalchemy/. [Accessed: ]
rf:citation
» Building RESTful APIs With Flask: An ORM With SQLAlchemy | Shalabh Aggarwal | Sciencx | https://www.scien.cx/2016/06/14/building-restful-apis-with-flask-an-orm-with-sqlalchemy/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.