An Application Programming Interface is a way for two different pieces of software to communicate. In the world of web services, APIs help make data available to third party applications. REST APIs are APIs built using the REpresentational State Transfer architectural style. The primary features are that they are stateless and provide a uniform interface.
This blog is intended to give you a quick hands-on in basic REST API development using Python and Flask, a popular web framework, and its extension SQLAlchemy.
Flask is a Python framework to build web applications and REST APIs. Its main job is to route incoming HTTP requests to appropriate functions in the application. SQLAlchemy is a Python SQL library and Object Relational Mapper (ORM) that enables communication with SQL databases.
What We need
· Python – Install latest version for your platform from https://www.python.org/
· PyCharm – This is the Python IDE. Install the community version from https://www.jetbrains.com/pycharm
· Flask - Steps to install this will be mentioned below
· SQLAlchemy - Steps to install this will be mentioned below
Our Goal is to build a simple API that exposes data related to movies such as movie name, language, genre, and IMDB rating. We will store our data in an SQLite db.
STEP 1: CREATE A NEW PYCHARM PROJECT
An important concept while working with Python projects is a virtual environment. It allows you to create an isolated Python environment, where all required packages for the project are installed. Simply put, our installation of Flask and SQLAlchemy will be within our project’s virtual environment. There are steps to create virtual environment directly from your systems' CLI. However, with Pycharm, it is automatically created for you.
Open PyCharm and create a new project. Rename the project as you wish, I am calling it FlaskDemo. As you can see below, PyCharm will create the virtual environment and set the path for Python interpreter to be used.
STEP 2: Install Flask and SQLAlchemy
Use the inbuilt Python package manager tool ‘pip’ for this. In your Pycharm terminal enter the following one after another.
pip install flask
pip install flask-sqlalchemy
If installation is successful, you should see these libraries in the left pane (Expand External Libraries->site-packages)
STEP 3: Setting up an initial Flask server
· Create a new Python file in project root directory with a preferred name. I am calling mine app.py
· Import Flask class and create its instance for this application
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return 'Hello!'
· Set FLASK_APP and FLASK_ENV environment variable in your current terminal to tell Flask which application to work with
· Start the server using ‘flask run’
· When you navigate to http://127.0.0.1:5000/ you should see ‘Hello!’ on the browser
STEP 5: Setting up a simple database
Here’s what we do in our code-
· Import SQLAlchemy and create its instance
· Configure our app to use an SQLite DB
· Define a class representing the Movie table that we will create in DB.
from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db'
db = SQLAlchemy(app)
class Movie(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), unique=True, nullable = False)
language = db.Column(db.String(80), nullable=False)
genre = db.Column(db.String(80), nullable=False)
rating = db.Column(db.Float)
def __repr__(self):
return f"{self.name} - {self.language} - {self.genre} - {self.rating}"
Next, we are going to run a few Python instructions directly from Python console to set up the DB. (note – this is NOT terminal, this is the Python interpreter environment where in you execute Python source instructions directly). Invoke the Python CLI by entering python in the terminal as below-
In this CLI, enter below Python instructions to set up the DB with two records (commands are in italics) -
from app import db
db.create_all() – at this point you will see the DB created and it will be shown in the project directory as data.db
from app import Movie
movie = Movie(name="Jurassic Park", language="English", genre="SciFi", rating=8.1)
db.session.add(movie)
db.session.commit()
Let’s enter one more record-
movie = Movie(name="Parasite", language="Korean", genre="Thriller", rating=8.6)
db.session.add(movie)
db.session.commit()
To query the DB –
Movie.query.all()
STEP 6: Defining routes and functions
So far, we have a basic server listening on our local port and connected to a DB. Now let’s crank up our application to work as an API servicing incoming HTTP requests. For this, Flask provides the ‘route’ decorator. Let me show you the code snippet to implement what can be done for an incoming POST request-
@app.route('/movies', methods = ['POST'])
def add_movie():
if request.is_json:
movie = Movie(name=request.json['Name'], language=request.json['Language'],
genre=request.json['Genre'], rating=request.json['IMDB rating'])
db.session.add(movie)
db.session.commit()
return jsonify({'Id':movie.id, 'Name':movie.name, 'Language':movie.language,
'Genre':movie.genre, 'IMDB rating': movie.rating}), 201
else:
return {'error': 'Request must be JSON'}, 400
And here is my code to implement incoming PUT request-
@app.route('/movies/<id>', methods=['PUT'])
def update_movie(id):
if request.is_json:
movie = Movie.query.get(id)
if movie is None:
return {'error': 'not found'}, 404
else:
movie.name = request.json['Name']
movie.language = request.json['Language']
movie.genre = request.json['Genre']
movie.rating = request.json['IMDB rating']
db.session.commit()
return 'Updated', 200
else:
return {'error': 'Request must be JSON'}, 400
In this manner, we define what needs to be done when the server receives an incoming HTTP request on an endpoint. You can find the full source code here. The following actions have been defined-
GET all movies on(/movies)
GET one specific movie using <id> on (/movies/<id>)
POST a new movie
Update a specific movie’s details using <id> on (/movies/<id>) using PUT
DELETE a movie using <id> on(/movies/<id>)
STEP 6: Testing our API
Now start your API by entering flask run into the terminal. I used POSTMAN to test the actions that are available. Here is what I get for GET and POST using POSTMAN. Go ahead and try the other methods after you have the complete server running.
GET –
POST –
GET again –
That’s it! We have our Flask API running.
Happy Coding!