What is this template?

This template creates a basic API that uses a username and password for initial login and then a JSON Web Token for subsequent access of the API. THe API includes routes for user management such as creating, deleting and modifying users.

Download it here

What is connexion?

Connexion is a framework that automagically handles HTTP requests based on OpenAPI Specification (formerly known as Swagger Spec) of your API described in YAML format. Connexion allows you to write an OpenAPI specification, then maps the endpoints to your Python functions; this makes it unique, as many tools generate the specification based on your Python code. You can describe your REST API in as much detail as you want; then Connexion guarantees that it will work as you specified.

You can find the library on GitHub.

By using Swagger it allows us to focus on the implementation of the API rather than worrying about ensuring data is present and serializing it e.g. making sure both a username and password are present in a login request.

The connexion library will use an openapi.yml file to define the endpoints of our API. This file define the URLs, request methods and requests data that each route will handle.

Project Layout

.
├── .env
├── app
│   ├── auth.py
│   ├── helpers.py
│   ├── __init__.py
│   ├── models
│   │   ├── __init__.py
│   │   └── user.py
│   ├── tests
│   │   ├── __init__.py
│   │   └── test_users.py
│   └── users.py
├── boot.sh
├── config.py
├── database.db
├── Dockerfile
├── migrations
│   ├── alembic.ini
│   ├── env.py
│   ├── README
│   ├── script.py.mako
│   └── versions
│       ├── 0bdd8c6a0514_.py
├── openapi
│   └── openapi.yml
├── requirements.txt
├── run.py
└── status_codes.py

Setup

First off, the .env file must be configured so that Flask can run our application

FLASP_APP=app
FLASK_DEBUG=true

Once done, the requirements must be installed. The easiest way to do this is via a virtual environment. After activing the new virtual environment the dependencies can be installed.

python3 -m venv venv
source venv/bin/activate
pip3 install -r requirements.txt

Once the dependencies are installed the API needs to be setup. Run the following commands to initialise Flask. This will setup the database

flask db init
flask db migrate
flask db upgrade

Extending

The OpenAPI documentation can be found here. Within existing OpenAPI file (./openapi/openapi.yml) there should be enough information to implement other routes to your liking. The operation ID is important as it tells swagger which function to run when a request is made to the API. It should also be noted that when parsing the OpenAPI file, the connexion library is incredibly strict about what is and isn’t legal.