FastAPI Course with Test-Driven Development | Dockerizing PostgreSQL

Posted by


In this tutorial, we will walk through how to create a Test Driven FastAPI course using FastAPI as the backend framework, PostgreSQL as the database, and Docker to containerize our application. By following this tutorial, you will learn how to write tests for your FastAPI application, set up a PostgreSQL database, and dockerize your application for easy deployment.

Test Driven Development (TDD) is a software development process where testing is done before writing the actual code. This helps in writing clean, efficient, and bug-free code. FastAPI is a modern web framework for building APIs with Python, which is known for its performance and ease of use. PostgreSQL is a powerful and open-source relational database management system that is widely used in production environments.

To get started with this tutorial, make sure you have Docker installed on your machine. You can download and install Docker from the official website (https://www.docker.com/get-started). Once you have Docker installed, you can follow the steps below to create your Test Driven FastAPI course.

Step 1: Setting up the FastAPI project
First, create a new directory for your FastAPI project and navigate to that directory in your terminal. Next, create a new virtual environment using the following command:

python -m venv env

Activate the virtual environment by running the following command:

source env/bin/activate (for Mac/Linux)
envScriptsactivate (for Windows)

Next, install the required dependencies for FastAPI by running the following command:

pip install fastapi uvicorn asyncpg

Create a new file named main.py in your project directory and add the following code to define a simple FastAPI application:

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def home():
    return {"message": "Hello, World!"}

To run your FastAPI application, use the following command:

uvicorn main:app --reload

You can now access your FastAPI application at http://localhost:8000 in your web browser.

Step 2: Writing tests for your FastAPI application
Now that you have set up the FastAPI project, it’s time to write tests for your application. Create a new directory named tests in your project directory and create a new file named test_main.py inside the tests directory.

Add the following code to the test_main.py file to define a test for the home endpoint:

from fastapi.testclient import TestClient
from main import app

client = TestClient(app)

def test_home():
    response = client.get("/")
    assert response.status_code == 200
    assert response.json() == {"message": "Hello, World!"}

To run the tests, use the following command:

pytest

You should see the test result displayed in the terminal.

Step 3: Setting up PostgreSQL database
Next, we will set up a PostgreSQL database for our FastAPI application. To do this, we will use Docker to run a PostgreSQL container. Create a new file named docker-compose.yml in your project directory and add the following code:

version: '3.8'

services:
  postgres:
    image: postgres
    environment:
      POSTGRES_USER: fastapi
      POSTGRES_PASSWORD: fastapi
      POSTGRES_DB: fastapi
    ports:
      - '5432:5432'

To start the PostgreSQL container, run the following command:

docker-compose up -d

You can verify that the PostgreSQL container is running by running the following command:

docker ps

Step 4: Dockerizing the FastAPI application
Now that we have set up the FastAPI project, written tests, and set up a PostgreSQL database, it’s time to dockerize our application. Create a new file named Dockerfile in your project directory and add the following code:

# Use the official Python image
FROM python:3.9

# Set the working directory in the container
WORKDIR /app

# Copy the current directory contents into the container at /app
COPY . /app

# Install any needed dependencies specified in requirements.txt
RUN pip install --no-cache-dir -r requirements.txt

# Make port 8000 available to the world outside this container
EXPOSE 8000

# Define environment variable
ENV DB_URL postgresql://fastapi:fastapi@postgres/fastapi

# Run main_fastapi.py when the container launches
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]

Create a new file named requirements.txt in your project directory and add the following line:

fastapi
uvicorn
asyncpg
pytest

Now, build the Docker image by running the following command:

docker build -t fastapi-docker .

To run the Docker container, use the following command:

docker run -d -p 8000:8000 fastapi-docker

You can access your FastAPI application running inside the Docker container at http://localhost:8000 in your web browser.

Congratulations! You have successfully created a Test Driven FastAPI course using FastAPI, PostgreSQL, and Docker. You have learned how to write tests for your FastAPI application, set up a PostgreSQL database, and dockerize your application for deployment. Feel free to explore more features of FastAPI and Docker to enhance your application further.

0 0 votes
Article Rating

Leave a Reply

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@timothyatanda1188
2 hours ago

Wow, what a great video!!!, amazing illustrations with explainations.

1
0
Would love your thoughts, please comment.x
()
x