Build and Deploy Your Flask API With a Postgres Database
Breakdown of the structure

Let’s dissect and learn about the structure of our cookiecutter template.

main.py — where everything starts

This is the entry point of the API request.

It contains the API endpoint and CLI declarations. It uses Flask-Restful for its APIs.

for its APIs. Creates the Flask app instance.

Uses Flask-Migrate to run SQLAlchemy migrations.

to run SQLAlchemy migrations. Imports the API resources.

src/main.py.

We might want to move the CLI functions when the file gets bigger.

app.py — where create_app resides

This contains the create_app() that returns the Flask app instance. The create_app() also accepts an env param which determines the environment where the app is running.

src/app.py.

config.py — your typical Python config file

This is our configuration file that supports multiple environments.

Database credentials are passed from environment variables. This makes it convenient for us to pass around credentials securely by avoiding writing them on the config file. Render provides a convenient way to pass database credentials to environment variables, without having to explicitly set those credentials. We’ll cover that in the later section about the render.yaml Infrastructure as Code.

src/config.py

utils.py — static and stateless functions

This is where we could add utility functions. It currently contains the get_env_variable() function.

src/utils.py

Resources — Flask Restful resources for the APIs

This contains the API resources implementation.

In the file below, you’ll see that it imports a repository class to create or get a user record stored in the database.

It uses Flask-Restful to make an abstraction to the API resources:

src/resources/user.py

Repositories — abstraction of data

This is where the calls to Flask-SQLAlchemy methods are made:

src/repositories/user.py

Models — represents our tables

In this directory, we declare how our data is stored and structured. The template includes a simple user model with the fields username , avatar_url , and date_created .

src/models/user.py

render.yaml — IaC for Render.com

This is the Infrastructure as Code (IaC) file to provide the resources and set up the deployment pipeline of our service in Render.com.

Below is an example of the implementation that can be found in the Flask Postgres Reference API. It instructs Render to create a web service resource, a Postgres database, and an environment variable group:
['Ardy Gallego Dedase']
['DevOps', 'Python', 'Programming', 'Flask', 'Software Engineering']