Skip to content

benitomartin/sam-lambda-aws-api

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

9 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Serverless API with AWS SAM, Lambda, Gateway and Docker

AWS, API Gateway, Lambda, SAM, Docker

A serverless API built with AWS SAM (Serverless Application Model) that generates random numbers within a specified range.

The project has been developed as part of the following blog

Table of Contents

Project Structure

├── lambda/
│   ├── lambda_function.py
├── .gitignore
├── .python-version
├── LICENSE
├── README.md
├── pyproject.toml
├── template.yaml
└── uv.lock

Prerequisites

  • Python 3.11
  • AWS SAM CLI
  • AWS CLI configured with appropriate credentials
  • Docker (for local testing)

Setup and Installation

  1. Clone the repository

    git clone https://github.com/benitomartin/aws-sam-lambda-dynamodb.git
    cd aws-sam-lambda-dynamodb
  2. Create a virtual environment and activate it (you can use uv or an other package manager):

    uv sync
    source .venv/bin/activate
  3. Build the SAM application:

    sam build

    This will create a .aws-sam directory with the built artifacts.

  4. Validate SAM template:

    sam validate

Testing the Function Locally

To invoke the function locally you need to activate Docker and run the following command. This will create a local AWS Lambda Docker image, invoke the function and return the response.

sam local invoke RandomNumberGeneratorFunction

Response:

{
    "random_number": 34
}

Alternatively, you can start the API locally and send requests to it. Here also Docker must be running and again a local AWS Lambda image will be created.

sam local start-api

The API will be available at http://127.0.0.1:3000

Send a POST request from a new terminal to generate a random number:

curl -X POST http://127.0.0.1:3000/generate-random \
-H "Content-Type: application/json" \
-d '{"min": 1, "max": 100}'

Response:

{
    "random_number": 5
}

Deployment to AWS

Deploy the app to your AWS account:

sam deploy --guided

Deployment via sam deploy --guided

Test the deployed function with the given endpoint, which also contains the StageName dev:

Deployed endpoint test

curl -X POST https://hi8mgf8ssl.execute-api.eu-central-1.amazonaws.com/dev/generate-random \
  -H "Content-Type: application/json" \
  -d '{"min": 1, "max": 100}'

Response:

{"random_number": 84}

Clean Up

To delete all AWS resources created:

sam delete

License

This project is licensed under the MIT License - see the LICENSE file for details.