In this guide, we integrate our PostgreSQL database with a Python/FastAPI application. Previously, we built a strong foundation in PostgreSQL by querying, inserting, updating, and deleting rows. Now, let’s combine these skills and set up a new table for our social media application. Before diving into the application code, perform a quick cleanup. In earlier demonstrations, we worked with a “products” table. If this table is no longer needed, you can remove it by right-clicking the table in your database management tool and selecting “Delete” or “Drop.” Otherwise, you may leave it intact—it won’t affect the FastAPI database integration.Documentation Index
Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
Use this file to discover all available pages before exploring further.
Ensure you are working with the designated FastAPI database. If you have multiple databases on your machine, ignore any unrelated entries and focus solely on your FastAPI-specific instance.
Schema Design for the Posts Table
For our social media application, we will create a new table called “posts.” The table will have the following columns:-
ID Column
- Type:
SERIAL(auto-incrementing integer primary key)
- Type:
-
Title Column
- Type:
VARCHAR(or character varying) - Constraint:
NOT NULL(each post must have a title)
- Type:
-
Content Column
- Type:
VARCHAR - Constraint:
NOT NULL
- Type:
-
Published Column
- Type:
BOOLEAN - Constraint:
NOT NULL - Default Value:
TRUE(defaults to true if not provided)
- Type:
-
Created_at Column
- Type:
TIMESTAMP WITH TIME ZONE - Constraint:
NOT NULL - Default Value: the current timestamp at the time of insertion
- Type:
FastAPI Application Code
Below is a snippet of our FastAPI application that defines a post schema using Pydantic and includes some sample posts:Creating the Posts Table
With the schema in mind, create the “posts” table in your FastAPI database using your preferred SQL tool or user interface. For initial testing, you can insert data directly. For example, to verify the contents of the posts table, run:You can use your SQL management tool to insert sample data into the posts table, ensuring that the correct structure and constraints are applied.