{"id":28881988,"url":"https://github.com/ronihdzz/aws-lambda-fastapi-template","last_synced_at":"2026-04-17T17:32:10.333Z","repository":{"id":283005969,"uuid":"949689826","full_name":"ronihdzz/aws-lambda-fastapi-template","owner":"ronihdzz","description":"Professional template for building serverless REST APIs with FastAPI, Docker, and AWS Lambda. Includes modular architecture, real database testing, and full CI/CD integration.","archived":false,"fork":false,"pushed_at":"2025-07-10T02:10:12.000Z","size":223,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-07-10T11:16:53.947Z","etag":null,"topics":["aws-lambda","ci-cd","cloud","docker","fastapi","github-actions","mangum","microservices","mongodb","postgresql","pydantic","python","rest-api","serverless","sqlalchemy","template","testing"],"latest_commit_sha":null,"homepage":"https://ronihdz.com/","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"gpl-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ronihdzz.png","metadata":{"files":{"readme":"README.es.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-03-17T01:23:10.000Z","updated_at":"2025-07-10T02:08:35.000Z","dependencies_parsed_at":"2025-05-11T23:20:50.614Z","dependency_job_id":"4b1cb8b6-24dd-4003-989c-d25fb2d9c7c6","html_url":"https://github.com/ronihdzz/aws-lambda-fastapi-template","commit_stats":null,"previous_names":["ronihdzz/aws-lambda-fastapi"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/ronihdzz/aws-lambda-fastapi-template","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ronihdzz%2Faws-lambda-fastapi-template","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ronihdzz%2Faws-lambda-fastapi-template/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ronihdzz%2Faws-lambda-fastapi-template/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ronihdzz%2Faws-lambda-fastapi-template/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ronihdzz","download_url":"https://codeload.github.com/ronihdzz/aws-lambda-fastapi-template/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ronihdzz%2Faws-lambda-fastapi-template/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":31938676,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-17T17:29:20.459Z","status":"ssl_error","status_checked_at":"2026-04-17T17:28:47.801Z","response_time":62,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.6:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["aws-lambda","ci-cd","cloud","docker","fastapi","github-actions","mangum","microservices","mongodb","postgresql","pydantic","python","rest-api","serverless","sqlalchemy","template","testing"],"created_at":"2025-06-20T20:41:45.037Z","updated_at":"2026-04-17T17:32:10.312Z","avatar_url":"https://github.com/ronihdzz.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# AWS Lambda FastAPI Template\n\n[![English](https://img.shields.io/badge/🇺🇸-English-blue)](README.md) [![Español](https://img.shields.io/badge/🇪🇸-Español-red)](README.es.md)\n\n| Environment | Coverage |\n|-----------|----------|\n| main | ![Coverage Badge](https://github.com/ronihdzz/aws-lambda-fastapi/blob/artifacts/main/latest/coverage.svg) |\n| development | ![Coverage Badge](https://github.com/ronihdzz/aws-lambda-fastapi/blob/artifacts/development/latest/coverage.svg) |\n\n## 📋 Template Description\n\nThis is a complete template for developing REST APIs with **FastAPI** designed to be deployed on **AWS Lambda** using **Mangum** as a reverse proxy. The template implements a complete **serverless** approach, providing modular architecture, standardized error handling, automated testing against real databases, and a comprehensive CI/CD stack with Docker.\n\n### 🚀 **Serverless \u0026 AWS Lambda Context**\n\nThe template is optimized for **serverless architectures** using AWS Lambda:\n- **Mangum** acts as an adapter/reverse proxy that allows FastAPI to function as a Lambda function\n- **Serverless Computing**: No server management, automatic scaling, pay-per-use\n- **API Gateway Integration**: Compatible with AWS API Gateway for routing and authentication\n- **Cold Start Optimization**: Structure optimized to minimize cold start time\n\n## 🏗️ Architecture and Project Structure\n\n### Directory Structure\n\n```\naws-lambda-fastapi/\n├── src/                          # Main source code\n│   ├── api/                      # API layer - Routers and endpoints\n│   │   ├── v1/                   # API versioning\n│   │   ├── routers.py            # Main router registration\n│   │   └── endpoints.py          # Base endpoints (health check, etc.)\n│   ├── core/                     # Central configuration\n│   │   ├── settings/             # Environment-specific configurations\n│   │   ├── exceptions.py         # Domain-specific exceptions\n│   │   └── internal_codes.py     # Domain internal codes\n│   ├── shared/                   # Shared utilities\n│   │   ├── middlewares/          # Custom middlewares\n│   │   ├── base_responses.py     # Standardized responses\n│   │   ├── base_internal_codes.py # Base internal codes\n│   │   ├── base_exceptions.py    # Base exceptions\n│   │   └── utils_dates.py        # Date utilities\n│   ├── db/                       # Database layer\n│   │   ├── postgresql/           # PostgreSQL configuration\n│   │   └── mongo/                # MongoDB configuration\n│   ├── tests/                    # Test suite\n│   └── main.py                   # Application entry point\n├── docker_images/                # Custom Docker images\n│   └── testing/                  # Testing configuration\n├── .github/workflows/            # CI/CD pipelines\n└── docs/                         # Project documentation\n```\n\n## 🔧 Main Components\n\n### 1. **Standardized Response System** (`@/shared/base_responses.py`)\n\nThis template implements a consistent response system using an **Envelope Response** pattern:\n\n```python\nclass EnvelopeResponse(BaseModel):\n    success: bool\n    message: str\n    data: dict[str, Any] | list | None = None\n    trace_id: str | None = None\n```\n\n**Conventions:**\n- All responses follow the same format\n- Automatic Pydantic model serialization handling\n- Trace_id inclusion for debugging\n- Structured error responses with internal codes\n\n### 2. **Internal Code System** (`@/shared/base_internal_codes.py`)\n\nStandardized error code system for tracking and debugging:\n\n```python\nclass CommonInternalCode(InternalCodeBase):\n    UNKNOWN = 100, \"Unknown error\"\n    PYDANTIC_VALIDATIONS_REQUEST = 8001, \"Failed Pydantic validations on request\"\n```\n\n**Conventions:**\n- Unique numeric codes for each error type\n- Clear error description\n- Extensible for domain-specific codes in `@/core/internal_codes.py`\n\n### 3. **Error Handling Middleware** (`@/shared/middlewares/`)\n\n#### CatcherExceptions\nMain middleware that catches all exceptions:\n- FastAPI HTTPException handling\n- SQLAlchemy NoResultFound handling\n- Custom exception handling\n- Automatic conversion to standardized response format\n\n#### CatcherExceptionsPydantic\nSpecific middleware for Pydantic validation errors:\n- Catches request body validation errors\n- Consistent validation error formatting\n\n### 4. **Configuration System** (`@/core/settings/`)\n\nEnvironment-based configuration using Pydantic Settings:\n\n```\nsettings/\n├── base.py           # Base configuration\n├── local.py          # Local development\n├── development.py    # Development environment\n├── staging.py        # Staging environment\n├── production.py     # Production environment\n└── testing.py        # Testing configuration\n```\n\n**Conventions:**\n- Typed environment variables\n- Automatic configuration validation\n- Environment-specific configuration\n- Multi-database support\n\n### 5. **Multi-Database System** (`@/db/`)\n\nTemplate prepared for multiple database managers with **functional examples**:\n\n#### PostgreSQL (`@/db/postgresql/`)\n```\npostgresql/\n├── base.py           # Base class for SQLAlchemy models\n├── connection.py     # Connection configuration\n├── models/\n│   └── public/       # 'public' schema\n│       └── book.py   # Example model\n└── __init__.py       # Main exports\n```\n\n- **SQLAlchemy 2.0**: Modern ORM with modern syntax\n- **Typed Models**: Full type hints and validation\n- **Singleton Connection**: Reusable and efficient\n\n#### MongoDB (`@/db/mongo/`)\n```\nmongo/\n├── base.py           # Base class for documents\n├── connection.py     # Configured MongoDB client\n├── models/           # Document models\n└── __init__.py       # Main exports\n```\n\n- **PyMongo**: Official MongoDB driver\n- **Pydantic Integration**: Models with automatic validation\n- **Async Ready**: Prepared for asynchronous operations\n\n**Conventions:**\n- Models organized by schemas/collections\n- Singleton connection pattern\n- Environment-specific configuration\n- **Extensible**: Easy to add Redis, DynamoDB, etc.\n\n### 6. **Modular API Structure** (`@/api/`)\n\nVersioning system and modular organization by domain:\n\n```\napi/\n├── v1/                    # API Version 1\n│   └── books/             # Domain module (example)\n│       ├── endpoints.py   # Defines REST endpoints\n│       ├── repositories.py # Database access\n│       ├── schema.py      # Pydantic models (DTOs)\n│       └── services.py    # Business logic\n├── routers.py             # Global router registration\n└── endpoints.py           # Base endpoints (health, index)\n```\n\n**Module Conventions:**\n- **endpoints.py**: Route definition and input validations\n- **services.py**: Business logic, orchestration\n- **repositories.py**: Data access, specific queries\n- **schema.py**: DTOs (Data Transfer Objects) with Pydantic\n\n**Scalability**: You can add more modules (`users/`, `orders/`, etc.) following the same structure.\n\n### 7. **Testing System** (`@/tests/`)\n\nComplete automated testing suite:\n\n```\ntests/\n├── common/           # Common utilities for tests\n├── utils/            # Testing utilities\n├── v1/               # Version-specific tests\n└── __init__.py       # Database configuration for tests\n```\n\n**Conventions:**\n- **Separate testing database**: Automatic configuration via `environment_testing`\n- **Reusable fixtures**: Common utilities in `tests/common/`\n- **Automated coverage**: Integrated in CI/CD with detailed reports\n- **Tests organized by version**: Modular structure by API version\n- **Automatic setup**: The `prepare_database()` script creates necessary schemas and tables each time the runner starts\n\n### 8. **Comprehensive Docker Stack** (`@/docker_images/`)\n\nThe project comprehensively organizes Docker images for different purposes:\n\n#### **Testing Docker** (`@/docker_images/testing/`)\nSpecialized configuration for testing against **real databases** (not mocks):\n\n- **`Dockerfile.testing`**: Optimized image for running tests\n- **`ci.env.sh`**: Script that configures environment variables for CI/CD\n- **`entrypoint.sh`**: Orchestrates test execution and report generation\n\n**Database Selection in CI:**\n```bash\n# In ci.env.sh you can select which databases to spin up\nexport POSTGRESQL_URL=\"${GITHUB_DATABASE_POSTGRESQL:-$POSTGRESQL_URL}\"\nexport MONGO_URL=\"${GITHUB_DATABASE_MONGODB:-$MONGO_URL}\"\nexport REDIS_URL=\"${GITHUB_DATABASE_REDIS:-$REDIS_URL}\"\n```\n\nTests run against **real instances** of PostgreSQL, MongoDB, and Redis in the GitHub Actions runner.\n\n#### **Build and Deploy Docker**\n- **`docker_images/build/`**: Optimized construction image\n- **`docker_images/deploy/`**: Final image for AWS Lambda deployment\n\n## 🚀 Complete CI/CD Pipelines\n\n### **Main GitHub Actions Flow**\n\nThe pipeline executes a complete and robust sequence:\n\n#### **1. 🔍 Linting (Pre-commit)**\n```yaml\n- Executes pre-commit for linting (configured in .pre-commit-config.yaml)\n- Code formatting with Black\n- Linting with Flake8  \n- Type checking with MyPy\n- Import and structure validation\n```\n\n#### **2. 🧪 Testing with Real Databases**\n```yaml\nservices:\n  postgres: # PostgreSQL 13 on port 5432\n  mongodb:  # MongoDB 4.4 on port 27017  \n  redis:    # Redis 6 on port 6379\n```\n- Spins up real database services\n- Runs tests against real instances (not mocks)\n- Generates detailed coverage reports\n\n#### **3. 📊 Coverage and Badges**\n- **Generation**: `coverage run`, `coverage xml`, `coverage-badge`\n- **Archival**: Uses `ronihdzz/git-archive-action@v3` to save artifacts\n- **Storage**: Reports are stored in dedicated `artifacts` branch\n- **Badges**: Dynamic coverage % badges are generated and displayed in README\n\n#### **4. 🏗️ Build and Deploy**\n- Docker image construction optimized for Lambda\n- Push to Amazon ECR (Elastic Container Registry)\n- Automatic deploy to AWS Lambda\n- Automatic versioning by environment (dev/staging/prod)\n\n### **Environment Configuration**\n\n```yaml\nBRANCH_ENV_MAP: \n  \"main\": \"prod\"\n  \"development\": \"dev\" \n  \"staging\": \"stg\"\n```\n\nEach branch automatically maps to its corresponding environment.\n\n## 📦 Dependencies and Technologies\n\n### Core Dependencies\n- **FastAPI**: Modern and fast web framework\n- **Mangum**: Adapter for AWS Lambda\n- **Pydantic**: Data validation and settings\n- **SQLAlchemy**: ORM for relational databases\n- **PyMongo**: MongoDB driver\n- **Loguru**: Advanced logging\n\n### Development Dependencies\n- **Pytest**: Testing framework\n- **Coverage**: Code coverage\n- **MyPy**: Type checking\n- **Pre-commit**: Pre-commit hooks\n\n## 🛠️ Development Commands\n\n### Run the project locally\n```bash\nuvicorn main:app --reload --port=9595\n```\n\n### Run tests\n```bash\npytest src/tests/ -v --cov=src\n```\n\n### Run pre-commit hooks\n```bash\npre-commit run --all-files\n```\n\n### Type checking\n```bash\nmypy src/\n```\n\n### Testing with Docker\n```bash\ndocker-compose -f docker-compose.yml up testing\n```\n\n## 🔍 Lambda Local Testing\n\nTo test the Lambda function locally:\n\n```bash\ncurl -X POST \"http://localhost:9100/2015-03-31/functions/function/invocations\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"version\": \"2.0\",\n    \"routeKey\": \"GET /\",\n    \"rawPath\": \"/\",\n    \"rawQueryString\": \"\",\n    \"headers\": {},\n    \"requestContext\": {\n      \"http\": {\n        \"method\": \"GET\",\n        \"path\": \"/\",\n        \"sourceIp\": \"127.0.0.1\"\n      }\n    },\n    \"isBase64Encoded\": false\n  }'\n```\n\n## 🎯 **Template Advantages**\n\n### **For Development**\n- **Serverless Ready**: Optimized for AWS Lambda with Mangum\n- **Multi-Database**: Native support for PostgreSQL, MongoDB, Redis\n- **Type Safety**: Full TypeScript-like experience with MyPy\n- **Error Handling**: Robust error handling system with internal codes\n\n### **For Testing**\n- **Real Databases**: Tests against real databases, not mocks\n- **Automated Setup**: Automatic creation of schemas and test data\n- **Coverage Tracking**: Detailed reports with automatic badges\n- **Docker Isolated**: Completely isolated testing environment\n\n### **For CI/CD**\n- **Full Pipeline**: Linting → Testing → Coverage → Build → Deploy\n- **Multi-Environment**: Automatic support for dev/staging/prod\n- **Quality Gates**: Pre-commit hooks and automatic validations\n- **Artifact Management**: Automatic storage of reports and badges\n\n### **For Production**\n- **AWS Optimized**: Configured for AWS Lambda + API Gateway\n- **Environment Config**: Typed configuration per environment\n- **Monitoring Ready**: Structured logging with Loguru + Sentry\n- **Scalable Architecture**: Modular structure easy to scale\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fronihdzz%2Faws-lambda-fastapi-template","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fronihdzz%2Faws-lambda-fastapi-template","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fronihdzz%2Faws-lambda-fastapi-template/lists"}