Production-grade FastAPI REST API — Containerized with Docker, deployed on Google Cloud Run, automated via GitHub Actions CI/CD.
- Architecture
- Tech Stack
- Project Structure
- API Endpoints
- Local Development
- Docker
- GCP Setup
- CI/CD Pipeline
- Monitoring & Logging
- Security
- Troubleshooting
- Resume Bullets
Developer ──git push──▶ GitHub ──triggers──▶ GitHub Actions
│
┌───────────┴──────────────┐
│ 1. Run tests (pytest) │
│ 2. Build Docker image │
│ 3. Push → Artifact Reg. │
│ 4. Deploy → Cloud Run │
└───────────┬──────────────┘
│
End User ──HTTPS──▶ Cloud Run URL ◀─── Deployed ────┘
│
┌─────────▼──────────┐
│ FastAPI Container │
│ (Uvicorn + Python) │
└─────────┬──────────┘
│ stdout logs
┌─────────▼──────────┐
│ Cloud Logging │
│ Cloud Monitoring │
└────────────────────┘
- Client sends
HTTPSrequest to the Cloud Run service URL - Cloud Run routes it to an available container instance
- Uvicorn (ASGI server) processes the HTTP connection
- FastAPI matches the URL path to the correct router handler
- Handler executes logic, writes a structured JSON log to stdout
- Cloud Logging ingests the stdout log automatically
- FastAPI returns a JSON response with latency headers
| Layer | Mechanism |
|---|---|
| GitHub → GCP Auth | Workload Identity Federation (no static keys) |
| Image storage | Private Artifact Registry (IAM-gated) |
| Runtime secrets | Cloud Run environment variables / Secret Manager |
| HTTPS | Enforced by Cloud Run (no plain HTTP) |
| Container user | Non-root (appuser, UID 1001) |
| IAM | Least-privilege service accounts per workload |
| Category | Technology |
|---|---|
| Language | Python 3.12 |
| Framework | FastAPI + Uvicorn |
| Containerization | Docker (multi-stage build) |
| Registry | GCP Artifact Registry |
| Compute | GCP Cloud Run (serverless) |
| CI/CD | GitHub Actions |
| Logging | Cloud Logging (structured JSON) |
| Monitoring | Cloud Monitoring + Uptime Checks |
| IAM | GCP Service Accounts + Workload Identity Federation |
CloudDeployX/
├── .github/
│ └── workflows/
│ └── deploy.yml # GitHub Actions CI/CD pipeline
├── app/
│ ├── __init__.py
│ ├── main.py # FastAPI app factory + middleware
│ ├── config.py # Pydantic-settings environment config
│ ├── logger.py # Structured JSON logger for Cloud Logging
│ ├── routers/
│ │ ├── health.py # /health, /health/live, /health/ready
│ │ └── items.py # CRUD endpoints for /api/v1/items
│ └── models/
│ └── item.py # Pydantic request/response models
├── tests/
│ └── test_main.py # Async pytest test suite (9 tests)
├── Dockerfile # Multi-stage production Dockerfile
├── .dockerignore
├── .env.example # Environment variable reference
├── .gitignore
├── requirements.txt
└── requirements-dev.txt
| Method | Path | Description |
|---|---|---|
GET |
/ |
API root — service info |
GET |
/health |
Health check with version info |
GET |
/health/live |
Kubernetes/Cloud Run liveness probe |
GET |
/health/ready |
Readiness probe with uptime |
| Method | Path | Description |
|---|---|---|
POST |
/api/v1/items |
Create a new item |
GET |
/api/v1/items |
List all items |
GET |
/api/v1/items/{id} |
Get single item |
PUT |
/api/v1/items/{id} |
Update an item |
DELETE |
/api/v1/items/{id} |
Delete an item |
Interactive API docs: https://<your-cloud-run-url>/docs
curl -X POST https://<your-cloud-run-url>/api/v1/items \
-H "Content-Type: application/json" \
-d '{
"name": "MacBook Pro",
"description": "16-inch M3 Pro laptop",
"price": 2499.99,
"in_stock": true
}'Response:
{
"id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
"name": "MacBook Pro",
"description": "16-inch M3 Pro laptop",
"price": 2499.99,
"in_stock": true,
"created_at": "2025-01-15T10:30:00Z",
"updated_at": "2025-01-15T10:30:00Z"
}- Python 3.12+
- Docker Desktop
- Git
git clone https://github.com/Mukunth1004/CloudDeployX.git
cd CloudDeployXpython -m venv .venv
source .venv/bin/activate # Linux/Mac
# .venv\Scripts\activate # Windowspip install -r requirements-dev.txtcp .env.example .env
# Edit .env with your valuesuvicorn app.main:app --host 0.0.0.0 --port 8080 --reloadApp is running at http://localhost:8080
Docs at http://localhost:8080/docs
pytest tests/ -vdocker build -t clouddeployx:local .docker run -p 8080:8080 \
-e APP_ENV=development \
-e LOG_FORMAT=text \
clouddeployx:localcurl http://localhost:8080/healthComplete step-by-step setup to connect this repo to Google Cloud.
export PROJECT_ID="clouddeployx-prod"
gcloud projects create $PROJECT_ID
gcloud config set project $PROJECT_ID
gcloud billing projects link $PROJECT_ID --billing-account=YOUR_BILLING_ACCOUNT_IDgcloud services enable \
run.googleapis.com \
artifactregistry.googleapis.com \
cloudbuild.googleapis.com \
logging.googleapis.com \
monitoring.googleapis.com \
iam.googleapis.com \
iamcredentials.googleapis.comgcloud artifacts repositories create clouddeployx-repo \
--repository-format=docker \
--location=us-central1 \
--description="CloudDeployX Docker images"gcloud iam service-accounts create github-actions-sa \
--display-name="GitHub Actions CI/CD Service Account"
SA_EMAIL="github-actions-sa@${PROJECT_ID}.iam.gserviceaccount.com"
# Grant required roles
gcloud projects add-iam-policy-binding $PROJECT_ID \
--member="serviceAccount:${SA_EMAIL}" \
--role="roles/run.admin"
gcloud projects add-iam-policy-binding $PROJECT_ID \
--member="serviceAccount:${SA_EMAIL}" \
--role="roles/artifactregistry.writer"
gcloud projects add-iam-policy-binding $PROJECT_ID \
--member="serviceAccount:${SA_EMAIL}" \
--role="roles/iam.serviceAccountUser"# Create WIF pool
gcloud iam workload-identity-pools create "github-pool" \
--project="${PROJECT_ID}" \
--location="global" \
--display-name="GitHub Actions Pool"
# Create WIF provider
gcloud iam workload-identity-pools providers create-oidc "github-provider" \
--project="${PROJECT_ID}" \
--location="global" \
--workload-identity-pool="github-pool" \
--display-name="GitHub Provider" \
--attribute-mapping="google.subject=assertion.sub,attribute.repository=assertion.repository" \
--issuer-uri="https://token.actions.githubusercontent.com"
# Allow GitHub Actions to impersonate the service account
gcloud iam service-accounts add-iam-policy-binding "${SA_EMAIL}" \
--project="${PROJECT_ID}" \
--role="roles/iam.workloadIdentityUser" \
--member="principalSet://iam.googleapis.com/projects/$(gcloud projects describe $PROJECT_ID --format='value(projectNumber)')/locations/global/workloadIdentityPools/github-pool/attribute.repository/Mukunth1004/CloudDeployX"Go to your repo → Settings → Secrets and variables → Actions and add:
| Secret Name | Value |
|---|---|
GCP_PROJECT_ID |
clouddeployx-prod |
WIF_PROVIDER |
projects/PROJECT_NUMBER/locations/global/workloadIdentityPools/github-pool/providers/github-provider |
WIF_SERVICE_ACCOUNT |
github-actions-sa@clouddeployx-prod.iam.gserviceaccount.com |
Every push to main triggers this workflow automatically:
git push → main
│
├─ Job: test
│ ├─ Checkout code
│ ├─ Set up Python 3.12
│ ├─ pip install requirements-dev.txt
│ ├─ ruff check (linter)
│ └─ pytest tests/ (9 tests)
│
└─ Job: deploy (only if tests pass)
├─ Authenticate to GCP (Workload Identity)
├─ Configure Docker for Artifact Registry
├─ docker build (multi-stage, cached)
├─ docker push :SHA + :latest
└─ gcloud run deploy (zero-downtime rollout)
Pull requests only run the test job — no deployment.
Every request produces a structured log visible in Cloud Logging:
{
"timestamp": "2025-01-15T10:30:00.123Z",
"severity": "INFO",
"message": "POST /api/v1/items → 201",
"service": "clouddeployx",
"version": "1.0.0",
"environment": "production",
"method": "POST",
"path": "/api/v1/items",
"status_code": 201,
"latency_ms": 12.4
}gcloud logging read "resource.type=cloud_run_revision AND resource.labels.service_name=clouddeployx" \
--limit=50 \
--format=jsongcloud monitoring uptime create \
--display-name="CloudDeployX Uptime" \
--resource-type=uptime-url \
--hostname=<your-cloud-run-url> \
--path=/health/live \
--period=60| Practice | Implementation |
|---|---|
| No static GCP keys | Workload Identity Federation |
| Least-privilege IAM | Separate service accounts per role |
| No secrets in images | Runtime env vars via Cloud Run |
| Non-root container | appuser (UID 1001) |
| HTTPS only | Enforced by Cloud Run |
| Secrets management | Cloud Secret Manager (ready to integrate) |
| Private image registry | GCP Artifact Registry (IAM-controlled) |
# Check Cloud Run logs
gcloud logging read "resource.type=cloud_run_revision" --limit=20# Re-run Docker auth configuration
gcloud auth configure-docker us-central1-docker.pkg.devVerify the WIF provider audience and the attribute.repository value matches exactly Mukunth1004/CloudDeployX.
Check structured logs in Cloud Logging Console under Logs Explorer:
resource.type="cloud_run_revision"
severity=ERROR
• Architected and deployed a production FastAPI REST API on Google Cloud Run
using Docker multi-stage builds, reducing image size by 60% vs naive builds.
• Implemented a zero-downtime GitHub Actions CI/CD pipeline that builds,
tests, and deploys on every push to main using Workload Identity Federation
(no static credentials).
• Configured GCP IAM with least-privilege service accounts, Artifact Registry
for private image storage, and structured JSON logging integrated with
Cloud Logging and Cloud Monitoring.
• Achieved auto-scaling from 0 to 10 Cloud Run instances with 80 concurrent
requests per instance, supporting burst traffic at zero idle cost.
MIT © Mukunth1004