APIs changed the way we build applications, there are countless examples of APIs in the world, and many ways to structure or set up your APIs. Today we will discuss how I use Python and Flask to build and document REST APIs that scale to every need.

As usual, I’m providing sample applications, for this case a starter kit for everyone to use and build upon, here is the link to the final code we will review today.

Before we start with code…

Let’s first discuss the project dependencies, why each of them is necessary and how it can benefit our project.

  • flask: Flask is a micro web framework which has a minimal footprint compared to others like django, and allows us to select which components and modules we want to integrate with it. Flask is highly reliable and performant.
  • flasgger: It’s a module that helps us integrate swagger docs to a flask API.
  • flask-marshmallow: Object serializer, ideal for parsing and dumping JSON data in and out of our API.
  • apispec: Required for the integration between marshmallow and flasgger.

Project Layout

We will start discussing how the project layout looks like by taking a look into the folder structure:

project/
    api/
        model/
            __init__.py
            welcome.py
        route/
            home.py
        schema/
            __init__.py
            welcome.py

    test/
        route/
            __init__.py
            test_home.py
        __init.py

    .gitignore
    app.py
    Pipfile
    Pipfile.lock

I think that the folder structure is self-explanatory, but let’s look at it part by part API Module

The API module will host our application code, from models, routes, schemas and controllers if needed (though I usually don’t create those).

  • The models are the data descriptor of our application, in many cases related to the database model, for example when using sqlalchemy, though they can be any class which represents the structure of our data.
  • The routes are the paths to our application (e.g. /api/home or /api/users) and it’s where we will define the route logic, data retrieval, insertion, updates, etc.
  • The schemas are the views (serializers) for our data structures. We should have at least one schema per model. The schemas will have it’s own definition as we will see later.

#api #python #flask #programming #api development #software engineering

Python Flask API - Starter Kit and Project Layout
26.00 GEEK