A SIMPLE API USING PYTHON AND FLASK

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)