An Introduction to the Falcon Framework
By: Esther Vaati
Tags: Python3, Data Science, Programming, Python, API

Building a RESTful API With Falcon

In this example, you will build a bucket list API. A bucket list is simply a list of things you’d like to do before you die. Let’s get started. Create the project directory and set up a virtual environment.

mkdir bucketlist

cd bucketlist

virtualenv .venv

source .venv/bin/activate

Install Falcon

Installing Falcon is as simple as:

pip install falcon

Create another folder app inside the bucketlist directory and mark it as a Python module by creating an empty __init__.py file in it:

mkdir app

touch app/__init__.py

Inside the app folder, create a file main.py and add the following code.

Falcon framework uses the concept of a resource. Resources are things that can be accessed by a URL. We will discuss this further when we start building the views for our application.

Edit main.py file to look something like this:

Falcon speaks WSGI, and so to serve a Falcon app, you will need a WSGI server. In this tutorial, we will be using Gunicorn to serve our app, so let’s install Gunicorn.

pip install gunicorn

Now run your application by issuing gunicorn -b 0.0.0.0:8000 — reload main:application . Navigate to http://127.0.0.1 , and you should see your representation of the IndexResource .

Let’s now get started on creating the blocks for our application:

Configure database

We will use the PostgreSQL database because it’s robust and stable.

PostgreSQL should be installed on your machine. Install the psycopg2 driver library in our application

pip install psycopg2

Create database and user

Create a database “bucketlist” and assign a user.

Switch over to the Postgres account on your machine by typing:

sudo su postgres

Access a Postgres prompt:

psql

Create bucketlist database:

CREATE DATABASE bucketlist;

Create role:

CREATE ROLE pat WITH LOGIN PASSWORD ‘my_password’;

Grant access to the user:

GRANT ALL PRIVILEGES ON DATABASE bucketlist TO pat;

We will use the SQLAlchemy extension to manage our application. This extension provides an ORM wrapper for the SQLAlchemy project.

Create a file config.py in the app directory and add the configurations you set up for the database above. The config file should look something like this.

Create models

Create a file models.py in the app directory and write the following code.

Here we declare a base class that all schema objects will inherit from. The to_dict function will manage our queries by returning results in dictionary form.

The declarative_base() returns a new base class from which all mapped classes should inherit.

In config.py , update the file to use our models. Here we use the base class from our models to declare metadata that will be used to issue CREATE statements for all tables in our models.

Requests and responses

Each responder in a resource receives a Request object that can be used to read the headers, query parameters, and body of the request.

HTTP request and HTTP response are represented by req and resp , respectively.

Create middleware for managing requests and responses

A middleware is a Python class that hooks into the request/response lifecycle.

Create a new file middleware.py in the app directory and add the following middleware class:

The class above demonstrates how to read headers and query parameters, handle errors, and how to work with request and response bodies.

Configure WSGI server to load the middleware and initialize the database

Edit the main.py file to include the middleware, and initialize the database as shown below.

Create resources

As we mentioned at the beginning of this tutorial, Falcon uses the concept of a resource, and Python classes usually represent these resources. They convert the incoming response into an action and deliver a response back to the client.

For a resource to provide support for any HTTP method, you add an on_*() method to the class, where * is any one of the common HTTP methods, in lowercase, i.e., on_get() , on_put() , etc.

Although resources are just regular classes, we are going to create a custom base class, BaseResource , from which we will inherit when we start creating our resources.

Let’s start by creating a tasks resource. In app/views.py add the following code to:

The TaskResource defines two methods, on_get() for obtaining all the recorded tasks and on_post() for adding a new task.

Create URLs

URLs provide a way for the client to identify resources uniquely.

Edit the main.py file to include the URL for the TaskResource as follows:

from app import views

application.add_route(‘/tasks/’, views.TaskResource())

Now, when a request comes in for /tasks , Falcon will call the responder on the task’s resource that corresponds to the requested HTTP method.

The project’s structure should now look like this:

Navigate to http://localhost:8000/tasks and see your resource in action.

Add a task

View tasks

Hooks

Hooks in Falcon are similar to Python decorators.

Suppose our application required the user to be logged in before they could add or view tasks. We would implement this with a before hook.

Let’s create a hook that will run before each request to view or add a task.

Next, we attach the hook to the on_post() responder and on_get() responders, as shown below.

Now, before every call to that responder, Falcon will first invoke login_required , giving the following response.

{

“title”: “401 Unauthorized”

}

Error handling

Falcon provides a set of error classes you can raise when something goes wrong, hence making it easier to detect and log errors.

These error classes include:

falcon.HTTPBadRequest

falcon.HTTPInvalidHeader

HTTPMissingHeader

HTTPInvalidParam