DEV Community

Cover image for How to build a Flask app with Neon serverless database
Ademola Thompson for Hackmamba

Posted on

How to build a Flask app with Neon serverless database

Using a serverless database eliminates the common pain points related to server management, configuration, and scalability. With a serverless database, you can focus solely on building your app while a service manages your database.

Neon is a fully managed serverless Postgres, offering many innovative features, including branching and bottomless storage. Neon offers a generous free tier that allows you to create more than one database and up to ten branches of each database.

In this tutorial, we’ll use Neon and SQLAlchemy, an object-relational mapper (ORM) that allows you to create SQL queries directly without writing SQL codes. Since Neon supports many technologies, including SQLAlchemy, you can integrate both to build your Flask application. Let’s get started!

Why do you need a serverless database?

The most obvious advantage is that it gives you a seamless experience when setting up a database for your application. This is because you don’t have to bother setting up a database manually, giving you a more straightforward and user-friendly process.
With a serverless database, you can save time and focus on important aspects of your application. Some other advantages include the following:

  • Scalability: Serverless databases are equipped to handle the scaling of resources based on your application’s demands. This means that as your application grows, the database will handle the increased workload without manual intervention from you.
  • Cost efficiency: Using serverless databases can help you cut costs, as you only pay for what you use, unlike traditional databases that charge a fixed amount for resources you might not use.
  • Reduced operational overhead: Serverless databases remove the need for you to manually manage database infrastructure. This reduces the operational burden on developers since they don’t have to worry about database updates, backups, and scaling.

How to set up a serverless database for your Flask application

You can find the code used in this tutorial on GitHub.

The following steps will show you how to set up a Neon serverless database for your Flask app.

Step 1: Signup on Neon

Navigate to Neon’s sign-up page and create an account. Signing up with your GitHub account is better because it allows you to automatically grant Neon access to your GitHub repositories. Neon needs this access to work properly.

Neon’s sign-up page

Step 2: Create a new project and database

After you sign up, Neon will prompt you to create a project and database. The page should look like this:

An interface to create a new project and database on Neon

You should fill out the fields with names for your project and database. You can also select a Postgres version and server location of your choice. Once you’re done, click on Create project.

Step 3: Get your database credentials from Neon

After you create a project on Neon, you will see a page where you can obtain your database credentials. Neon has different syntax for the frameworks it supports, but it is preferable to stick to the default database URL for easy integration for your Flask app. Copy the database URL to a safe place.

Neon’s interface, showing database credentials with an arrow pointing to the clipboard icon.

After you get your database credentials, you can create a Flask project and connect it to your Neon database.

How to connect a Flask application to Neon serverless database

These next steps will show you how to create and connect a Flask application to a Neon database.

Step 1: Install Flask and other dependencies

To use Flask and Neon together, you’ll need to install three significant dependencies. You can install them by typing the following command in your command line interface (CLI):

pip install flask sqlalchemy psycopg2-binary

NOTE: You can install psycopg2 as an alternative to psycopg2-binary, especially for Mac and Linux OS.

Step 2: Create a Flask app

Create a new directory for your project, and create a file called app.py to serve as the base file for your project. Inside your new file, initiate your Flask application. Here’s a simple code snippet you can use:

#app.py
from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return "Home Page!"
Enter fullscreen mode Exit fullscreen mode

You can run the above code by typing this command in your CLI:

flask --app app run --debug

The command above will work if your file name is app.py. Otherwise, you should follow this syntax:

flask --app your_file_name run --debug

If you run into any trouble, check out the official documentation for Flask.

Step 3: Connect your Flask app to Neon using SQLAlchemy

There are three steps involved in connecting your Flask app to Neon:

  1. Import SQLAlchemy into your project.
  2. Add your database URL to your app configuration.
  3. Create a model and migrate it to the database.

Here’s what the code should look like:

#app.py
# Import SQLAlchemy
from flask_sqlalchemy import SQLAlchemy

# Add your database URL to create a database object.
app.config["SQLALCHEMY_DATABASE_URI"]= "your_database_url_from_neon"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db = SQLAlchemy(app)

# Create a simple model
class Book(db.Model):
    book_id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String)

# Commit your model (table) to the database
with app.app_context():
    db.create_all()
Enter fullscreen mode Exit fullscreen mode

The above code snippet configures the app to use your Neon database. It also creates a model called Book with only two fields, the ID and title, and commits them to the database.

NOTE: The value of app.config["SQLALCHEMY_DATABASE_URI"] should be the database URL you copied from Neon earlier. Also, remember that the database URL has your password encoded in it! While it’s fine to hardcode the connection string to get started quickly, you’ll want to store the database URL in an environment variable and import it like:

app.config["SQLALCHEMY_DATABASE_URI"]=os.environ.get('DATABASE_URL_ENV_VAR", "")

Neon will create a new table for your model with the new modification to your code. To view your new database table, follow the steps below:

  1. Navigate to your project dashboard. Neon will redirect you to this page immediately after you create a project.
  2. Click on the “Tables” option on the left pane.
  3. Your new table will be on the page you get redirected to.

Neon’s page to show the structure of tables users create

You can create another model if you want. It will appear on Neon in the same manner.

Step 4: Create an endpoint to populate your table

You can test your new table by creating an endpoint that performs operations on the table. An example is an endpoint that adds new objects to the table:

# app.py
from flask import request, jsonify # New imports

@app.route('/add_book', methods=['POST'])
def add_book():
    if request.method == 'POST':
        data = request.get_json()

        # Validate if the required fields are present in the request
        if 'title' not in data:
            return jsonify({'error': 'Missing title'}), 400

        title = data['title']

        # Create a new Book instance and add it to the database
        new_book = Book(title=title)
        db.session.add(new_book)
        db.session.commit()
        return jsonify({'message': 'Book added successfully'}), 201
Enter fullscreen mode Exit fullscreen mode

The above code snippet creates a new endpoint (/add_book/) for your app. This endpoint takes the title of a new book and creates a new book instance in the database.

You can test this endpoint with a tool like Postman. Navigate to http://127.0.0.1:5000/add_book and make a post request, as shown in this image:

Testing an endpoint on postman

Next, check on Neon to confirm that your database has new data in it:

Neon’s interface to show objects in a table created by a user

You can add as many items as you want. You can create other endpoints to edit, delete, or perform other actions on your database objects. Neon will help you visualize those changes directly.

How to branch your database in Neon

Neon allows you to branch your database like a repository on GitHub. This feature allows you to create a copy of your database and use it for testing purposes.

With branching, you can assign a copy of your database to different developers during the development phase of your app. This will make your work more organized and prevent database conflicts. It will also save you the cost of paying for different database services. The following steps will show you how to create and use a database branch in Neon:

Step 1: Create a new branch

Select Branches from the left pane of the Neon interface. After that, click on New Branch.

Neon’s branching page

Next, fill out the form with the necessary information, such as the name of your branch. When you’re done, click on Create a branch.

Creating a new branch on Neon

Step 2: Test your branched database

After you create a new branch, you will see a modal containing the database credentials for your newly branched database. Copy the database URL:

Database connection string for a database on  Neon

Next, replace your database URL with the new one. This is the line of code you need to modify:
app.config["SQLALCHEMY_DATABASE_URI"]="your_new_database_url_from_neon"

Next, you can add items to the database with the endpoint you created earlier. To view your new item(s), navigate to the Tables section and switch to your new branch.

Neon’s table page showing the table objects created by the user

If you switch back to your first branch, it won’t contain the new data you added. This is useful for developers to work with their test data during development.

Streamline your Flask development with Neon

Building a Flask application will always be easier if you don’t have to worry about a custom database infrastructure. With a tool like Neon, you can use a Postgres database without requiring extensive configuration and manual setup. Depending on your project's requirements, you also get the luxury of writing little to no SQL queries.

The branching feature of Neon can also boost productivity if you are working with other team members who want to test out different data in the database.

Continue development on the Flask app to match your use case!

References

You can learn more about Flask, Neon, and SQLalchemy through these links:

Top comments (0)