A minimal yet production-ready FastAPI application demonstrating core backend engineering concepts including structured configuration, health checks, logging, and testing patterns.
This project demonstrates a clean, scalable backend architecture with the following layers:
├── app/
│ ├── config.py # Environment-based configuration
│ ├── main.py # FastAPI application factory
│ ├── routers/ # API endpoint organization
│ │ ├── health.py # Health check endpoints
│ │ └── echo.py # Echo service endpoints
│ └── utils/
│ └── logging.py # Structured logging setup
├── tests/ # Integration tests
├── .env # Environment configuration
└── requirements.txt # Python dependencies
- Separation of Concerns: Each layer has a single responsibility
- Configuration Management: Environment-based config with validation
- Observability: Structured logging and comprehensive health checks
- Testability: Dependency injection and integration testing
- Production Readiness: Proper error handling and monitoring endpoints
- Python 3.8+
- pip or poetry for dependency management
- Clone and setup environment:
git clone https://github.com/DanielPopoola/fastapi-microservice-health-check.git
cd fastapi-microservice-health-check
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
- Install dependencies:
pip install -r requirements.txt
- Configure environment:
cp .env.example .env
# Edit .env with your configuration
- Run the application:
uvicorn app.main:app --reload
The API will be available at http://localhost:8000
Endpoint | Purpose | Use Case |
---|---|---|
GET /health |
Comprehensive health check | Monitoring dashboards |
GET /health/live |
Liveness probe | Kubernetes liveness |
GET /health/ready |
Readiness probe | Kubernetes readiness |
{
"status": "healthy",
"timestamp": 1640995200.123,
"version": "1.0.0",
"checks": {
"database": {
"status": "healthy",
"duration_ms": 23.4
},
"redis": {
"status": "healthy",
"duration_ms": 12.1
}
}
}
Endpoint | Method | Description |
---|---|---|
GET /echo |
GET | Echo service with query parameter |
POST /echo |
POST | Echo service with request body |
# Query parameter echo
curl "http://localhost:8000/echo?msg=hello"
# Response: {"echo": "hello"}
# Request body echo
curl -X POST "http://localhost:8000/echo" \
-H "Content-Type: application/json" \
-d '{"message": "hello world"}'
# Response: {"echo": "hello world"}
Configuration is managed through environment variables with sensible defaults:
Variable | Default | Description |
---|---|---|
APP_NAME |
FastAPI Health Check Demo | Application name |
DEBUG |
false | Debug mode |
LOG_LEVEL |
INFO | Logging level |
HOST |
0.0.0.0 | Server host |
PORT |
8000 | Server port |
Variable | Default | Description |
---|---|---|
HEALTH_CHECK_TIMEOUT |
5.0 | Health check timeout (seconds) |
DATABASE_URL |
None | PostgreSQL connection string |
REDIS_URL |
None | Redis connection string |
# Development
DEBUG=true
LOG_LEVEL=DEBUG
# Production
DATABASE_URL=postgresql://user:pass@localhost:5432/mydb
REDIS_URL=redis://localhost:6379/0
HEALTH_CHECK_TIMEOUT=3.0
The application uses structured logging with different formats for development and production:
- Colorized console output
- Human-readable format
- Detailed tracebacks
- JSON format for log aggregation
- Structured fields for filtering
- Performance metrics
{
"timestamp": "2024-01-01 12:00:00.000",
"level": "INFO",
"module": "app.routers.health",
"function": "health_check",
"line": 123,
"message": "Health check completed: healthy",
"http_method": "GET",
"http_path": "/health",
"duration_ms": 45.2
}
# Run all tests
pytest
# Run specific test file
pytest tests/test_endpoints.py
# Run with verbose output
pytest -v
The project uses integration tests that verify the entire request/response cycle:
# Example test
async def test_health_endpoint():
async with AsyncClient(app=app, base_url="http://test") as client:
response = await client.get("/health")
assert response.status_code == 200
assert response.json()["status"] == "healthy"
Tests use a separate configuration to avoid interfering with development:
# Test settings override
def create_test_settings(**overrides):
"""Create test settings with optional overrides."""
defaults = {
"app_name": "FastAPI Test App",
"debug": True,
"log_level": "INFO",
"database_url": None,
"redis_url": None,
"health_check_timeout": 1.0
}
defaults.update(overrides)
return Settings(**defaults)
The application implements three types of health checks following industry best practices:
-
Liveness Check (
/health/live
)- Answers: "Is the process running?"
- Use for: Kubernetes liveness probes
- Action if failing: Restart the pod
-
Readiness Check (
/health/ready
)- Answers: "Can the app serve requests?"
- Use for: Kubernetes readiness probes
- Action if failing: Remove from load balancer
-
Comprehensive Check (
/health
)- Answers: "Is everything working optimally?"
- Use for: Monitoring dashboards
- Action if failing: Alert operations team
All health checks and requests are logged with structured data for metrics collection:
- Response times
- Error rates
- Dependency health trends
- Request patterns
app/
├── config.py # Centralized configuration management
├── main.py # FastAPI application factory
├── routers/ # API endpoint organization
│ ├── __init__.py
│ ├── health.py # Health check logic
│ └── echo.py # Business logic endpoints
└── utils/ # Shared utilities
├── __init__.py
└── logging.py # Logging configuration
- Create a new router file in
app/routers/
- Define your endpoints using FastAPI decorators
- Add the router to
main.py
- Write integration tests in
tests/
The project follows these conventions:
- Type hints for all function parameters and returns
- Pydantic models for request/response validation
- Structured logging for all operations
- Comprehensive error handling
- Dependency injection for testability
This project demonstrates several backend engineering concepts:
- Configuration Management: Pydantic BaseSettings
- Dependency Injection: FastAPI's dependency system
- Structured Logging: Loguru with JSON formatting
- Health Checks: Kubernetes-ready health endpoints
- Testing: Integration testing with httpx
- Error Handling: Proper HTTP status codes and error responses
This project is licensed under the MIT License - see the LICENSE file for details.