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
- Project Structure
- Prerequisites
- Setup and Installation
- Testing the Function Locally
- Deployment to AWS
- Clean Up
- License
├── lambda/
│ ├── lambda_function.py
├── .gitignore
├── .python-version
├── LICENSE
├── README.md
├── pyproject.toml
├── template.yaml
└── uv.lock
- Python 3.11
- AWS SAM CLI
- AWS CLI configured with appropriate credentials
- Docker (for local testing)
-
Clone the repository
git clone https://github.com/benitomartin/aws-sam-lambda-dynamodb.git cd aws-sam-lambda-dynamodb
-
Create a virtual environment and activate it (you can use
uv
or an other package manager):uv sync source .venv/bin/activate
-
Build the SAM application:
sam build
This will create a
.aws-sam
directory with the built artifacts. -
Validate SAM template:
sam validate
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
}
Deploy the app to your AWS account:
sam deploy --guided
Test the deployed function with the given endpoint, which also contains the StageName dev
:
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}
To delete all AWS resources created:
sam delete
This project is licensed under the MIT License - see the LICENSE file for details.