How to Connect a FastAPI Server to PostgreSQL and Deploy on GCP Cloud Run

How to Connect a FastAPI Server to PostgreSQL and Deploy on GCP Cloud Run
By Management
May 28

How to Connect a FastAPI Server to PostgreSQL and Deploy on GCP Cloud Run

FastAPI is a Python web framework that allows you to build APIs quickly and efficiently. PostgreSQL is a popular open-source SQL database management system that can be used with FastAPI. In this tutorial, we will be discussing how to connect a FastAPI server to PostgreSQL and Deploy on GCP Cloud Run.

Setting up a PostgreSQL Database

Firstly, you need to create a new PostgreSQL database instance if you haven’t already done so. You can use various tools such as Docker or other cloud service providers to set up your PostgreSQL instance. Once you have set up your PostgreSQL instance, make sure you have the hostname, port number, username, and password for your database. This information will be needed when configuring the connection between FastAPI and PostgreSQL.

Now you can create a new database and tables within your PostgreSQL instance. This can be done using SQL commands or a tool like pgAdmin. Make sure to take note of the table and column names as we will refer to them in our FastAPI code later on.

You can also add some initial data to the tables if required. This will help in testing our FastAPI server later on.

Connecting FastAPI to PostgreSQL

In order to establish a connection between FastAPI and PostgreSQL, we will be using a third-party package called ‘SQLAlchemy’. SQLAlchemy is an open-source SQL toolkit and ORM (Object Relational Mapping) library for Python. It provides a set of high-level API for working with relational databases. We’ll be using SQLAlchemy’s ‘create_engine()’ function to create a database engine object that will represent our PostgreSQL connection.

Here’s how you can configure the connection between FastAPI and PostgreSQL:

<img src=”connection.png”>

We first import the necessary modules and define some constants to store the database credentials. We then create a database engine object using SQLAlchemy’s ‘create_engine()’ function and pass in the connection string which contains all the necessary information for connecting to our PostgreSQL instance.

You can customize the connection string based on your database configuration. Here, we are using f-strings to inject the database credentials into the connection string.

Defining Models with Pydantic

Pydantic is a data validation library that provides runtime validation and serialization/deserialization of data structures. It allows you to define data models as Python classes in a concise way. Pydantic models can be used to validate incoming data and also to serialize outgoing data. We are going to use Pydantic to define our data models for the FastAPI application.

We’ll define two models – a User model and a Task model. Here’s how the models look like:

<img src=”models.png”>

We define the User and Task models as Python classes that inherit from the Pydantic’s ‘BaseModel’ class. We define the attributes of each model along with their types. Pydantic comes with built-in data types (like ‘str’, ‘int’, ‘float’, etc.) but it also allows you to create custom types as well. For example, we define the ‘datetime’ type for the ‘completed_at’ attribute of the Task model.

Creating a CRUD API with FastAPI

FastAPI makes it easy to create a CRUD (Create, Read, Update, Delete) API with just a few lines of code. We’ll define our API endpoints for creating, reading, updating, and deleting user tasks. We’ll also add some input validation and error handling to our API.

Here’s how our FastAPI application code looks like:

<img src=”crud.png”>

We define a FastAPI ‘app’ object and import our database engine object. We then define the API endpoints using FastAPI’s ‘api_router’ decorator and use FastAPI’s ‘Depends’ to inject dependencies like the database connection and data models. We implement the CRUD functionality using a combination of SQLAlchemy queries and FastAPI response models.

Testing the FastAPI Server Locally

Before deploying our FastAPI server to GCP Cloud Run, it’s a good idea to test it locally. You can use tools like ‘curl’ or ‘Postman’ to make HTTP requests to the API endpoints and verify that everything is working as expected.

You can start the FastAPI server locally by running the following command:

uvicorn main:app –reload

This command starts the FastAPI server at http://localhost:8000. You can then make requests to the API endpoints using ‘curl’ or ‘Postman’.

Deploying the FastAPI Application to GCP Cloud Run

GCP Cloud Run is a fully managed compute platform that automatically scales your containers. It provides an easy way to deploy and run containerized applications in a serverless environment.

Here are the steps to deploy our FastAPI application to GCP Cloud Run:

  • Build a Docker image of the FastAPI application using the Dockerfile.
  • Push the Docker image to a container registry, such as Google Container Registry (GCR).
  • Create a new Cloud Run service and deploy the Docker image from the container registry.

In this tutorial, we have learned how to connect a FastAPI server to PostgreSQL and deploy the application to GCP Cloud Run. We used a combination of SQLAlchemy, Pydantic, and FastAPI to create a CRUD API for user tasks. FastAPI provides a simple and efficient way to create APIs with Python and allows for easy integration with relational databases like PostgreSQL. GCP Cloud Run provides an easy-to-use platform for deploying and scaling containerized applications in a serverless environment.

Leave your Comment