Build a Movie Data API With Python: Part 1

Summary

Welcome to part one of my series on how to develop and deploy a Python API. In this tutorial, we’ll be using Flask, a popular Python web framework, to retrieve and manipulate data from a movie reviews database that we’ll create.

What you’ll learn in this course

  • How to build a REST API in Python supporting CRUD operations.
  • Unit testing with Pytest and adding continues integration with CircleCI.
  • How to use Docker to containerize our API for deployment.
  • Deploy our API on the internet using AWS EC2.

Prerequisites

  • Intermediate knowledge of the command line.
  • Basic Python Syntax.
  • Git fundamentals.

Let’s Begin!

In this article we’re going to cover how to configure and start the API server.

Create Project Directory

First, we’ll create an empty directory in which we’ll like to have our project. Name it movie_data_api. Once it’s created cd, into that directory.

$: mkdir movie_data_api && cd ./movie_data_api

Specify Dependencies

We’re then going to create a requirements.txt . This file is where we specify the python libraries we’ll be using for this project. Using your preferred editor create the requirements file and add the following lines.

Flask==1.0.2
pytest==3.6.1
sqlalchemy==1.2.10

Run pip install -r requirements.txt to install our dependencies. We can now start writing our API!

Create The API File

In our project directory create the python file api.py . Now the fun begins!

Add the following line to the top of the api.py .

from flask import Flask, jsonify

Here we’re importing Flask and a flask function called jsonify which allows us to return data in JSON format.

Add a blank line and the following line.

app = Flask(__name__)

Here we’re initializing an instance of Flask. Read here to understand the purpose of __name__.

We’re now going to add our first API endpoint!

Paste the following code two lines below the above command.

@app.route("/", methods=["GET"])
def test():
    return jsonify({
"code": 200,
        "message": "Hello, World"
    })

This function can be split into three parts.

@app.route("/", methods=["GET"])

This is referred to as a decorator. Placing this line with the route method above a functions tells Flask to run this function when a request is made to the / route. This function would run when a request is made to http://localhost:4000/.

return jsonify({
"code": 200,
    "message": "Hello, World"
})

jsonify converts an argued dictionary into JSON. This functions return a JSON response to the client that makes the API request. We’ll see examples of this when we test our API.

At the bottom of our file add the follow if block.

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=4000, debug=True)

This part confused me when I first started programming in Flask.

if __name__ == "__main__":

The __name__ variable in Python is the name of the python file that is first called to the start the program. __name__ equals "__main__" when the current file is the first called. This block will only run when we call python api.py.

app.run(host="0.0.0.0", port=4000, debug=True)

This line tells Flask how we wan’t our API to run.

host="0.0.0.0" : Tells Flask to run on localhost.

port=4000 : Tells Flask to run on http://localhpst:4000 .

debug=True : Flask will return error message if our code breaks.


You api.py file should look like this.

Starting and Testing

To start our api run the following command on the command line.

$: python api.py

You’ll get output like this.

* Serving Flask app "api" (lazy loading)
* Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
* Debug mode: on
* Running on http://0.0.0.0:4000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 189-960-685

Our API is running. To send our first request go to http://localhost:4000 in your browser. You can also test form the command line by running curl -X GET http://localhost:4000.

You should receive a response like this.

{
"code": 200,
"message": "Hello, World"
}

Congratulations! You have written an API in Flask. To stop the API server press control + c on your keyboard. However, if we want to have a fully functioning movie reviews service then we have allot more to do.

Next Time…

In the next chapter of this series, we’ll use a popular SQL database called Postgres to store our movie data. We’ll also write API functions (endpoints) to retrieve, add, edit, and delete movie data. Stay tuned!