This article demonstrates retrieving posts from a PostgreSQL database using Python with FastAPI and psycopg2, covering database connection and API endpoint creation.
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.
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.
Copy
Ask AI
while True: try: conn = psycopg2.connect( host='localhost', database='fastapi', user='postgres', password='password123', cursor_factory=RealDictCursor ) cursor = conn.cursor() print("Database connection was successful!") break except Exception as error: print("Connecting to database failed") print("Error:", error) time.sleep(2)my_posts = [{"title": "title of post 1", "content": "content of post 1", "id": 1}, ...]
The output log may include messages similar to the following:
Copy
Ask AI
Connecting to database failedError: FATAL: password authentication failed for user "postgres"WARNING: WatchGodReload detected file change in 'C:\Users\sanje\Documents\Courses\fastapi\app\main.py'. Reloading...Database connection was successful!INFO: Started server process [26976]INFO: Waiting for application startup.INFO: Application startup complete.
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:
Copy
Ask AI
Connecting to database failedError: FATAL: password authentication failed for user "postgres"WARNING: WatchGodReload detected file change in 'C:\Users\sanje\Documents\Courses\fastapi\app\main.py'. Reloading...Database connection was successful!INFO: Started server process [22420]INFO: Waiting for application startup.INFO: Application startup complete.INFO: 127.0.0.1:53076 - "GET /posts HTTP/1.1" 200 OK
When making a request via Postman, the endpoint may return a response like:
Copy
Ask AI
[ { "title": "title of post 1", "content": "content of post 1", "id": 1 }, { "title": "favorite foods", "content": "I like pizza", "id": 2 }]
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.
WARNING: watchGodReload detected file change in 'C:\Users\sanje\Documents\Courses\fastapi\app\main.py.dfbc928ea7d1f64e03ca5f2a29d1b.tmp'. Reloading...Database connection was successful!INFO: Started server process [20880]INFO: Waiting for application startup.INFO: Application startup complete.INFO: 127.0.0.1:52499 - "GET /posts HTTP/1.1" 200 OK
When a GET request is made, the JSON response from the database could be:
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.