Python FastAPI Serializers and Controllers Lab Solution
About
This repo contains the solution code for the Python FastAPI Serializers and Controllers Lab
Getting Started
-
Fork and clone this repo.
-
Navigate into the project directory:
cd python-fastapi-serializers-and-controllers-lab-solution- Install dependencies (this also creates the virtual environment if it doesn’t exist):
pipenv install- Activate the virtual environment:
pipenv shell-
Set up your PostgreSQL database:
- Ensure PostgreSQL is installed and running on your machine.
- Create a database named
teas_dbif it does not already exist:
createdb teas_db- Open the application in Visual Studio Code:
code .- The database connection string is defined in the
config/environment.pyfile:
db_URI = "postgresql://<username>@localhost:5432/teas_db"Modify your database connection string to use your username as the
<username>.
-
Seed the database with initial data:
- Run the
seed.pyfile to reset the database by dropping existing tables and repopulating it with starter data:
- Run the
pipenv run python seed.pyYou should see output indicating the database was successfully seeded. If there are any errors, check the
db_URIin theconfig/environment.pyfile.
- Start the development server:
pipenv run uvicorn main:app --reloadYou should now have the app running. Visit
http://127.0.0.1:8000in your browser to confirm it’s working.
- Now you can test each endpoint using FastAPI’s built-in documentation.
Navigate to FastAPI Documentation: Open
http://localhost:8000/docsin your browser.
Troubleshooting PostgreSQL
-
The database connection string is defined in the
config/environment.pyfile: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 existit 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.