Skip to main content
In this lesson, we demonstrate how to retrieve posts from a PostgreSQL database using Python with FastAPI and psycopg2. The guide covers establishing a database connection, executing a SQL query to retrieve posts, and defining the corresponding API endpoints. This tutorial will help you integrate SQL operations seamlessly into your FastAPI applications.

Establishing a Database Connection

The code below continuously attempts to connect to your PostgreSQL database. Using the RealDictCursor ensures that query results are returned as dictionaries, making them easier to work with. Although an initial in-memory array of posts (my_posts) is defined for demonstration purposes, later in the lesson, the actual database results are used.
The output log may include messages similar to the following:

Defining FastAPI Routes

Root Endpoint

The root endpoint returns a simple greeting message to confirm that the server is up and running.

Retrieve Posts Endpoint

In this section, we define an endpoint that retrieves posts directly from the PostgreSQL database. The code executes a SQL query to fetch all posts and returns the retrieved data as JSON.
A sample log output after fetching posts might look like this:
When making a request via Postman, the endpoint may return a response like:

Create Post Endpoint

This endpoint demonstrates how to create a new post. The incoming post is converted to a dictionary, given a random ID, and appended to the in-memory posts array. In a production environment, the new post would be written to the database.
After the application starts, you might see log statements such as:
The consolidated final version of the endpoints is shown below:
The final log output may appear as:
When a GET request is made, the JSON response from the database could be:

Final Thoughts

Integrating SQL within your Python code using FastAPI is straightforward once you understand the basic operations such as executing queries and fetching results. This lesson has illustrated how to establish a PostgreSQL database connection, retrieve posts with SQL queries, and expose common operations via FastAPI endpoints.
Remember, in production environments, it is best to write changes directly to the database rather than relying on in-memory arrays.

Watch Video