FastAPI and Docker: A Guide to Test-Driven Development

Posted by


Test-Driven Development (TDD) is a software development approach where tests are written before implementing the code. This helps in ensuring that the code meets the requirements and works as expected. In this tutorial, we will use FastAPI, a modern web framework for building APIs with Python, and Docker, a platform for developing, shipping, and running applications in containers, to practice Test-Driven Development.

Prerequisites:
Before we begin, make sure you have the following installed on your system:

  • Python (preferably version 3.6 or later)
  • Docker

Step 1: Setting up the project
Create a new directory for your project and navigate to it in the terminal:

mkdir fastapi-docker-tdd
cd fastapi-docker-tdd

Next, create a new Python virtual environment inside the project directory:

python3 -m venv env

Activate the virtual environment:

source env/bin/activate

Now, install FastAPI and Uvicorn (ASGI web server) using pip:

pip install fastapi uvicorn

Step 2: Writing the first test
Create a new directory called "tests" inside the project directory:

mkdir tests

Create a new Python file called "test_main.py" inside the "tests" directory. This file will contain our test cases:

import unittest

class TestMain(unittest.TestCase):
    def test_hello_world(self):
        assert 1 + 1 == 2

if __name__ == '__main__':
    unittest.main()

Step 3: Running the test
To run the test, execute the following command:

python -m unittest tests/test_main.py

If the test passes, you will see an output similar to the following:

.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

Step 4: Writing the API code
Create a new Python file called "main.py" in the project directory. This file will contain the API code:

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def read_root():
    return {"Hello": "World"}

Step 5: Running the API
To run the API using Uvicorn, execute the following command:

uvicorn main:app --reload

Navigate to http://localhost:8000 in your browser to see the API running. You should see a JSON response displaying "Hello: World".

Step 6: Building the Docker image
Create a new file called "Dockerfile" in the project directory. This file will contain instructions for building the Docker image:

FROM tiangolo/uvicorn-gunicorn-fastapi:python3.8

COPY ./app /app

Next, create a file called "docker-compose.yml" in the project directory. This file will define the services for our Docker environment:

version: '3'

services:
  app:
    build: .
    ports:
      - "8000:80"
    volumes:
      - ./app:/app

Step 7: Running the Docker container
To build and run the Docker container, execute the following command:

docker-compose up -d --build

Navigate to http://localhost:8000 in your browser to see the API running inside the Docker container.

Step 8: Writing more tests
Now that we have our API running inside a Docker container, let’s write more tests to test its functionality.

Create a new test file called "test_api.py" inside the "tests" directory. This file will contain test cases for the API endpoints:

import unittest
from fastapi.testclient import TestClient
from main import app

client = TestClient(app)

class TestAPI(unittest.TestCase):
    def test_read_main(self):
        response = client.get("/")
        assert response.status_code == 200
        assert response.json() == {"Hello": "World"}

if __name__ == '__main__':
    unittest.main()

Step 9: Running the new tests
To run the new tests, execute the following command:

python -m unittest tests/test_api.py

If the tests pass, you will see an output similar to the following:

.
----------------------------------------------------------------------
Ran 1 test in 0.001s

OK

Conclusion:
In this tutorial, we have learned how to do Test-Driven Development with FastAPI and Docker. We wrote tests before implementing the code, ran the tests, built a Docker image for our API, and ran it inside a container. Test-Driven Development can help in ensuring the quality and reliability of your code. Remember to always write tests for your code to catch any bugs early in the development process.

0 0 votes
Article Rating

Leave a Reply

5 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@tonyleotta6715
2 hours ago

Does the actual course include videos?

@ernestoperezamigo4866
2 hours ago

Hello, the course is a series of articles on the web or videos?

@saurabhmehta7681
2 hours ago

Looks great!

@2ndx
2 hours ago

Just picked up this course myself and for $25 to get tips to improve my current fastapi stack is well worth it.

@dhavalsavalia
2 hours ago

Hiiii, I'm interested in this course, but $25 in my part of the world is very steep and almost equivalent of 1/4 of my monthly stipend and challenging to arrange especially in these times. I request you if you can adjust to PPP, if possible. Thanks and stay safe!

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