Building a Practical Serverless API with SAM: Leveraging Nested Stacks for Organization

This example demonstrates how to build and deploy a simple serverless API using AWS Lambda, API Gateway, and AWS SAM (Serverless Application Model). The core focus here is on leveraging modularity and nested stacks to create a well-organized and scalable project structure. Project Structure Here’s a quick overview of the project’s key components: api.yaml: This SAM file defines the API Gateway. It’s responsible for linking HTTP paths (like /orders and /logs) to the appropriate Lambda Functions. Crucially, it imports the API definition from openapi.yaml. log.yaml: This SAM file contains the definition for the Lambda Function responsible for fetching logs (GetLogs). order.yaml: This SAM file contains the definition for the Lambda Function responsible for fetching orders (GetOrders). openapi.yaml: This is the OpenAPI (Swagger) file that specifies the API paths (e.g., /orders, /logs) and how they integrate with the Lambda Functions. Here, we define the x-amazon-apigateway-integration that links each path to the ARN of the relevant Lambda Function. template.yaml: This is the main SAM template for your project. It acts as an orchestrator for all the sub-stacks (OrderStack, LogStack, ApiStack). Each sub-stack points to its respective YAML file using the Location property of AWS::Serverless::Application. Why Modularity and Nested Stacks? Modularity & Organization: When you split your project into separate files like order.yaml, log.yaml, and api.yaml, your project becomes easier to organize and understand. Each file focuses on one part of the app, so it’s easier to work on and update, especially when the project gets bigger. ...