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:
- Ensure PostgreSQL is installed and running on your machine.
- Create a database named
teas_db
if it does not already exist:
createdb teas_db
Seed the database with data:
- Run the
seed.py
file to reset the database by dropping existing tables and repopulating it with starter 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 theconfig/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
-
The database connection string is defined in the
config/environment.py
file:db_URI = "postgresql://<username>@localhost:5432/teas_db"
- Ensure your PostgreSQL instance is configured to allow connections with the provided credentials.
- Modify your database connection string to use your username as the
<username>
.
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.