FastAPI Serializers and Controllers Setup

Setup

In this Lesson, we’ll start by working with a pre-existing application that utilizes a PostgreSQL database instance, SQLAlchemy models and a database seeded with initial data.

If you have a complete, working application from the Python FastAPI SQLAlchemy Relationships Lesson, you may choose to use that codebase as starter code instead of the repo provided below.

1. Clone the starter code

We’ve provided a starter repository with the base application code. Clone the repository to your local machine and rename the folder for this lesson:

git clone https://git.generalassemb.ly/modular-curriculum-all-courses/python-fastapi-sqlalchemy-relationships-solution python-fastapi-serializers-and-controllers

2. Install dependencies:

This project uses pipenv for managing dependencies. To install everything the project needs, run:

 pipenv install

3. Activate the virtual environment:

 pipenv shell

4. Set up the database:

Set up your PostgreSQL database:

createdb teas_db

Seed the database with data:

pipenv run python seed.py

You should see output indicating the database was successfully seeded. If there are any errors, check the db_URI in the config/environment.py file.

5. Start the development server:

pipenv run uvicorn main:app --reload

You should now have the app running. Visit http://127.0.0.1:8000 in your browser to confirm it’s working.

Open the application in Visual Studio Code:

code .

Notes on Configuration

Setting Up a User in PostgreSQL

To connect to a specific PostgreSQL user, use the following command:

psql -U <username>

Handling “Role Does Not Exist” Error

If you see this error:

Error: FATAL: role "<username>" does not exist

it means that the specified user does not exist in PostgreSQL.

Creating a New PostgreSQL User

To create the user, run the following command inside psql:

CREATE ROLE "<username>" WITH LOGIN PASSWORD 'your_secure_password';

🔹 Replace <username> with your desired username and choose a secure password.

This will allow you to connect using one of the following database connection strings:

Connection Strings:

If no password is required:

db_URI = "postgresql://<username>@localhost:5432/teas_db"

If a password is required:

db_URI = "postgresql://<username>:<your_secure_password>@localhost:5432/teas_db"

This ensures that PostgreSQL correctly authenticates and allows access to the teas_db database.