Contents

A Useful Template to Build and Deploy Your Flask API With a Postgres Database

A Useful Template to Build and Deploy Your Flask API With a Postgres Database

A useful template to help you spin up your next project and start building.

https://cdn-images-1.medium.com/max/800/1*ZeZEg-xS7KMOqoGdQgMMMQ.jpeg

Source: Unsplash

We often find ourselves rewriting the same boilerplate code — like configuration, structure, and the build and deployment setup — when writing a Flask web service. The goal of this article is to help you minimise doing eating the same thing over and over in your next Flask API project. You will also learn how to deploy your Flask web service with a database live onRender.com. If you don’t use Render, no problem — thiscookiecutteralso uses Docker to help facilitate build and deployment on other platforms.


What’s Included in the Template

  • Go live with a continuous deployment pipeline using GitHub and Render’s Infrastructure as Code. See sampleIaC file here.
  • Works with SQLAlchemy/Postgres DB out of the box.
  • Usesmypyfor static type checks.

High-level structure

Below is the structure of our Flask API. We will go through each file or component in the next section.

https://cdn-images-1.medium.com/max/800/1*O_PEPxbh_9OqdkMtOU4jkA.png High-level structure of the cookiecutter template.


Breakdown of the structure

Let’s dissect and learn about the structure of ourcookiecuttertemplate.

main.py — where everything starts

This is the entry point of the API request.

  • It contains the API endpoint and CLI declarations. It usesFlask-Restfulfor its APIs.
  • Creates the Flask app instance.
  • UsesFlask-Migrateto run SQLAlchemy migrations.
  • Imports the API resources.

View Code on GitHub Gist

src/main.py.

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

app.py — where create_app resides

This contains thecreate_app()that returns the Flask app instance. Thecreate_app()also accepts anenvparam which determines the environment where the app is running.

View Code on GitHub Gist

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 therender.yamlInfrastructure as Code.

View Code on GitHub Gist

src/config.py

utils.py — static and stateless functions

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

View Code on GitHub Gist

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 usesFlask-Restfulto make an abstraction to the API resources:

View Code on GitHub Gist

src/resources/user.py

Repositories — abstraction of data

This is where the calls toFlask-SQLAlchemymethods are made:

View Code on GitHub Gist

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 fieldsusername,avatar_url, anddate_created.

View Code on GitHub Gist

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 theFlask Postgres Reference API. It instructs Render to create a web service resource, a Postgres database, and an environment variable group:

View Code on GitHub Gist

We mentioned earlier in theconfig.pysection about how we use the environment variable in our configuration. Notice theenvVarswhich is handy in passing to environment variables the credentials from the Postgres database. You’ll also notice theenvVargroups— this is where we can set our own environment variable values.


Run Locally

Now that we’re familiar with the structure of our cookiecutter template, let’s run one locally.

Pre-requisite

Before we start, ensure that you have cookiecutter installed. Details about theinstallation can be found here.

pip install cookiecutter

Once cookiecutter is installed, you need to “cookie-cut” the template:

cookiecutter git@github.com:ardydedase/cookiecutter-flask-postgres-api.git

After running the command above, you’ll be asked to enter your project details as illustrated below. Enter the values accordingly, note that the project slug value will be used as your GitHub repository name and your project folder name.

https://cdn-images-1.medium.com/max/800/1*CRPkUNGPzwbrLiUVFccwjQ.png Cookicutter template project details.

This will generate the project for you. Change the directoryto the project folder that was created by the cookiecutter.

cd <project_slug>

Rundocker-composein the root folder of the project:

docker-compose up

After successfully running withdocker-compose, you can check your Flask app running locally athttp://localhost:5000/healthcheck.

You can also check out theREADMEon GitHub for other ways to run the app locally.


Deploying with Render.com

Please note that this will incur some costs in your Render bill — more about theirpricing here.

Using Render is pretty straightforward. After logging in to Render, click the “YAML” link in the menu, which is on this page:https://dashboard.render.com/iacs.

Click the “New from YAML” and select the render.yaml file from the root folder of the project generated from the cookiecutter. After uploading the YAML file, Render will ask you to approve the resources that the IaC will create. More about usingRender’s IaC here.

More about managing Render’s resourcesin their docs.

After successful deployment in Render, a URL to your service will be provided in the Render dashboard.


Next Steps

Hopefully, you’re now able to quickly create and deploy your own Flask API with Postgres Database!

Check out theFlask API with Postgres Cookiecutter Templateon GitHub. It also comes with aReference Repository— a sample project built from our cookiecutter.

Check out my other post aboutCookiecutter Template for building NPM packages here.