Build a RESTful Flask API - The TDD Way - scotch.io Tutorial 1 Notes

27 Nov 2017

The Build a RESTful Flask API - The TDD Way tutorial by Jee Gikera is one of the best tutorials I have followed and it seemed to meet an impossible combination of my learning needs (Flask + API + TDD + Python + PostgreSQL + SQLAlchemy). Jee’s attention to detail and scalable architecture are two areas missing sometimes from other tutorials.

Below are my notes after completing the first tutorial. The name of my project used throughout these notes is strobla and Activity is the data model.

Where’s my project GitHub link? I am using Atlassian Bitbucket as a free private source code repository whilst my project is in its early stages. Open sourcing my project, either through Bitbucket or GitHub, is a decision I’ll make later..

Virtual Environment

On Windows, autoenv did not set environment variables from .env when I cd into the project folder.

After trying alternatives (source, etc), I created the following file in my home directory:

The .env_.ps1 file can be easily run each time you open a new PowerShell console. The file also helps to keep secrets out of the version-controlled project directory.

APP_STAGE replaces APP_SETTINGS in my project and was changed as a personal preference and readability. Throughout my notes, I will make minor changes to variable names however I recommend using the same directory structures and naming conventions.

Environment Configurations

I pointed the Testing database URI to a new environment variable to keep passwords out of source control. Also note the different environment names I am using..

Data Model

My project uses retrieves JSON data from the Strava API and saves it into the Postgres database. For simplicity, my table contains two columns:

id : Derived from the JSON data instead of auto creating new IDs

data : a JSONB type Postgres column to store the JSON object

When issuing PUT API calls, I was getting Duplicate Key errors. I added an update() function to the model to support all PUT calls. An alternative is to use Activity.query.filter_by(id=id).update() within app\__init__.py.

API Functionality

A note separate to the tutorial is the handling of JSON data through the API. When submitting JSON through the API, eg. self.client().put('/activities/id, data={JSON}'), the JSON must be wrapped in a json.dumps() call to avoid Flask ValueErrors. Similarly, use json.loads() to convert back to the original JSON format.

A minor change was made to the PUT section to use activity.update() instead of .save() and the DELETE section was changed as follows as I was unable to get the tutorial code to work:

Conclusion

The tutorial helps understand how the numerous pieces fit together in a fully-featured Flask-based API application. I was able to adapt my project easily to fit within this architecture and continue learning how to write Python code. Looking forward to Part 2..