Login

Lost your password?
Don't have an account? Sign Up

How to implement a RESTful API with Flask and Python


Do you use Flask…? You will.

Tharuka Sewwandi

Various benefits offered by Python, like simplicity and elegance attract most of the web developers to build web applications using python. When it comes to web applications, Web APIs have experienced a significant increase in popularity and usage in the past few years. Flask is a powerful and widely used microweb framework for creating APIs in python. From this article, we are going to build a simple RESTful API for an online songs web application and this might be helpful for beginner developers and anyone interested in getting up and running with flask.

Before you start following this guide, you will need:

  • A local python-3 environment installed in your machine

To get started, you’ll need to create a new directory to develop your flask project and head over to the directory as follows.

Want to read this story later? Save it in Journal.

> mkdir songs-api> cd songs-api

To implement the flask project first create a virtual environment inside the directory. The purpose of having a virtual environment is to create an isolated environment for python projects so that each project can have its own dependencies regardless of the dependencies in other projects. And inside that virtual environment, you can install flask. The good news is we can do both tasks as mentioned using one command.

> pipenv install flask

If the installation process successfully completed you will see the below output in the terminal.

figure 1: Output of the installation process

Once Flask is installed you’ll need to install SQLAlchemy in your virtual environment. SQLAlchemy is a database toolkit and object relational mapper (ORM ) implementation written in Python. The installation of SQLAlchemy can be done as follows.

> pipenv install flask-sqlalchemy

After the installation process, we’ll go ahead and start the virtual environment using the below command.

> pipenv shell

Meanwhile, you can open your project from an IDE that supports python. It is recommended Pycharm as the best IDE for developing Python code since it is providing a productive user experience for Python developers, or you can use any other IDE as you prefer. Create another folder called ‘api’ to include the API implementation.

FLASK_APP

We must tell the virtual environment where to find our application in order to use it. For that, we can use an environment variable called ‘FLASK_APP’ and it will help to specify how to load the application. In this example, I will set the FLASK_APP to be ‘api’. Hence it will allow flask to run on whatever is inside of the api folder.

Unix Bash

$ export FLASK_APP=hello

Windows CMD

> set FLASK_APP=hello

FLASK_DEBUG

Set FLASK_DEBU equal to 1 which implies ‘true’, and as a result, when we run the app it is already in the debug mode so when we do any changes in the code it automatically restarts the application and we don’t need to restart it just before running the application.

Unix Bash

$ export FLASK_DEBUG=1

Windows CMD

> set FLASK_DEBUG=1

Inside the api directory, we are going to create 3 files and the content inside these files will be discussing in this article

__init__.py file

We include an __init__.py file when we want a folder to be considered as a Python package.

We start the implementation by importing flask and SQLAlchemy. Line 3 will instantiate FLAaSK SQLAlchemy and it is going to initialize inside the ‘create_app’ function. Line 5 will start implementing the create_app function which is the application factory function and the purpose of having this kind of function is to have multiple instances of the same application running in the same application process. Inside the function, we can create an application object as shown in line 7 and ‘__name__’ implies the name of the current python module and it is used as a convenient way of telling where the current python module is located to set up some paths.

In order to do the application configuration in line number 8, we are using the SQLite database since this is a very small application. And underneath the configuration, we are going to call the db object initialized in line number 3 then pass the app object.

Finally, we can import the views.py file and register the blueprint named ‘main’ created inside the views.py. This will call both api endpoints within the create_app function

views.py file for routing

In this file, we are going to define all the endpoints of the api and in this example, I’m going to create two endpoints respectively view all songs and add a song.

Line 5 instantiating a blueprint class object called “main” to move all api calls into a blueprint, so that we can de-couple the application into smaller and reusable components. The code from line 7 to line 13 will implement the first endpoint to add songs and there we name the endpoint as ‘/add_songs’ and give the method as ‘POST’ since the first endpoint is regarding a post request. In order to add a song into the database first, we get the data from the request as a JSON file in line 9. From lines 10 to 12 we create a new song object using the song model from models.py file and add the data received from the request into the song database and commit it.

From line 15 we start the implementation of the second endpoint to view all songs with the name of the endpoint as ‘/songs’ and the method as ‘GET’. Using the song class defined in the models.py file we can query the song table as shown in line 17. But we cannot send songs list directly to jsonify because the list is the result of the SQLAlchemy query and it doesn’t work as JSON data. Therefore as in lines 19 and 20, we convert the songs list into a dictionary. Finally, the function returns a list of songs through a JSON object while converting the array of songs list into JSON data using jsonify.

models.py file for database initialization

In this file, we will include a class that initiates the songs table.

The very first line will import the db object created inside the __init__.py file. And rest of the code will implement the class represents the song table. There are 3 columns in the song table respectively, ‘id’, ‘title’, and ‘rating’.

After the api implementation, you need to create the database and connect this application with the database. Once you successfully connect the database with the application you can finally start up the application.

> flask run

This command will show the URL where our application is running.

* Running on http://127.0.0.1:5000

You can use postman to test the application by calling endpoints respectively,

http://127.0.0.1:5000/songs to view all songs and http://127.0.0.1:5000/add_songs to add songs

In this article, I have covered only the restful APIs for GET and POST requests and it is pretty easy to build APIs with flask. Even though SQLite database is more straightforward and easier to connect with python applications, it is not recommended to use in large scale applications, because as your application scales SQLite is not powerful to handle a lot of data. However, you can use MongoDB, PostgreSQL, and MySQL to connect large scale applications.

Hopefully, you can now implement your own RESTfull API using Flask and I look forward to discussing how to create and connect the SQLite database to a flask application and connect the React front end to this web application in my later articles.

Thank you for going through this article and feel free to leave a few claps if you found this helpful.

Latest code is available in https://github.com/tharuka-amaraweera/RESTful-API-Flask.git



Source link

https://avasta.ch

Leave a Comment

Your email address will not be published. Required fields are marked *

*
*