Skip to content

04. Health Endpoint & Tests

We will continue working on "Initial FastAPI App" issue from Milestone 1: Project Scaffolding.

4.1 Update README.md

Before diving into code, let's update our project documentation.

  1. Verify Branch: Ensure you are still on the fastapi-setup branch.

    git checkout fastapi-setup
    
    (You should already be on this branch from the previous section.)

  2. Update README.md:

  3. Open README.md
  4. Download the example README.md (or simply plan to update the text).
  5. Replace the template text with:

    • Project Name
    • Team Members (Just you for now)
    • Project Description
    • Technologies Used
    • Setup Instructions
  6. Commit and Push:

    git add README.md
    git commit -m "docs: update README with project details
    
    closes #1"
    git push origin fastapi-setup
    
    (Replace #1 with your actual issue number for "Update README")

4.2 Add Health Check Endpoint

We are going to add a health check endpoint to our FastAPI application.

The health endpoint is a simple API endpoint that returns a JSON response indicating the status of the application. This is useful for monitoring and ensuring that the application is running correctly.

  1. Open app/main.py
  2. Add the health check endpoint:
from fastapi import FastAPI

app = FastAPI(title="CSE120 GitHub Workshop")

@app.get("/health")
async def health_check() -> dict[str, str]:
    return {"status": "ok"}
  1. Start the FastAPI server if it's not already running:

The FastAPI development server will automatically reload if it's still running since we are using development mode(dev).

However, if it's not running, start it with:

uv run fastapi dev

View the new endpoint in the interactive API docs at http://localhost:8000/docs.

You can also navigate to http://localhost:8000/health in your browser to see the response.

4.3 Commit the Health Endpoint

Let's commit the changes we made to add the health endpoint.

VS Code UI: 1. Go to the Source Control panel (icon with three branches) 2. Stage all changes by clicking the + icon next to Changes 3. In the message box, type:

```
feat: add health check endpoint

closes #2
```

*Note: Replace `<issue-number>` with the actual issue number of "Initial FastAPI App", e.g., `1`.*
  1. Click the checkmark icon to commit

Terminal:

Alternatively, you can run the following commands in the terminal:

Stop the FastAPI server if it's running with Ctrl+C.

Then open your terminal and run.

git add .
git commit -m "feat: add health check endpoint

closes #<issue-number>"
git push origin fastapi-setup

Note: Replace <issue-number> with your actual health endpoint issue number.

4.4 Add Tests for Health Endpoint

Update Project Board

  1. Go to your repository on GitHub
  2. Navigate to the Projects tab
  3. Open your project board
  4. Find the issue card for "Add first tests" (should be in "Todo" or "Backlog" column)
  5. Drag the card to the "In Progress" column

4.5 Install Testing and Quality Tools

We will add testing and quality tools to our project.

  • Pytest: A testing framework for Python that makes it easy to write simple and scalable unit test cases. Unit testing is a software testing method where individual units or components of a software are tested in isolation to ensure that they work as expected. Learn more about Pytest.

    For example, we will add unit tests to verify that our health endpoint works correctly.

  • Mypy: An optional static type checker for Python that aims to combine the benefits of dynamic (or "duck") typing and static typing. Type checking is the process of verifying and enforcing the constraints of types. It helps to catch type-related errors before they occur at runtime. Learn more about MyPy.

    For example, a function annotated to return an int will raise an error if it tries to return a str.

  • Ruff: A fast Python linter written in Rust. Linting is the process of running a program that will analyze code for potential errors. It helps to ensure that the code adheres to a certain style and can catch common mistakes. Learn more about Ruff.

    For example, Ruff can catch unused library imports or variables that are defined but never used.

Add pytest, mypy, and ruff as dependencies

Stop the FastAPI server if it's running with Ctrl+C.

Then open your terminal and run.

uv add pytest mypy ruff --dev

Note: The --dev flag adds these packages to the dev dependency-groups in pyproject.toml. Which means they will only be installed in development environments and not in production.

4.6 Create Test File

Let's create our first unit test. It will test our health endpoint.

  1. Create a tests directory in your project root
  2. Create test_health.py in the tests directory with the following content:
from fastapi.testclient import TestClient
from app.main import app

client = TestClient(app)

def test_health():
    resp = client.get("/health")
    assert resp.status_code == 200
    assert resp.json() == {"status": "true"}

4.7 Run Tests

Run pytest to execute your tests:

uv run pytest

Notice: The test fails! This is intentional - the test expects {"status": "true"} but the endpoint returns {"status": "ok"}.

4.8 Fix the Test

Update test_health.py to expect the correct response.

Replace

assert resp.json() == {"status": "true"}

with

assert resp.json() == {"status": "ok"}

4.9 Verify Tests Pass

Run pytest again:

uv run pytest

All tests should now pass!

4.10 Run Quality Checks

Run mypy and ruff to check for type issues and linting problems.

uv run mypy app
uv run ruff check

You should see no issues reported.

4.11 Commit Test Changes

Let's commit the changes we made to add tests for the health endpoint.

VS Code UI: 1. Go to the Source Control panel (icon with three branches) 2. Stage all changes by clicking the + icon next to Changes 3. In the message box, type:

```
test: add tests for health endpoint

closes #3
```

Note: Replace `#<issue-number>` with the actual issue number for "Add first tests".
  1. Click the checkmark icon to commit

Terminal: Alternatively, you can run the following commands in the terminal: Stop the FastAPI server if it's running with Ctrl+C.

Then open your terminal and run.

git add .
git commit -m "test: add tests for health endpoint

closes #<issue-number>"

Note: Replace #<issue-number> with the actual issue number for "Add first tests".


Learn more

Understanding TestClient

FastAPI's TestClient is built on top of httpx and allows you to test your API without running a server:

client = TestClient(app)  # Create test client
response = client.get("/health")  # Make requests
assert response.status_code == 200  # Verify responses

Benefits: - No need to start the server - Tests run faster - Easy to integrate with pytest - Supports all HTTP methods (GET, POST, PUT, DELETE, etc.)

Why Testing Matters

  • Catch bugs early: Find issues before they reach production
  • Confidence in changes: Refactor without fear
  • Documentation: Tests show how your code should be used
  • Regression prevention: Ensure old bugs don't come back

Useful Resources