{"id":20067699,"url":"https://github.com/ae9is/py-lambda-docker","last_synced_at":"2026-04-11T17:03:16.638Z","repository":{"id":227896133,"uuid":"762943164","full_name":"ae9is/py-lambda-docker","owner":"ae9is","description":"Example api with Lambda + SAM + Docker + Pytorch","archived":false,"fork":false,"pushed_at":"2024-02-25T09:24:23.000Z","size":48,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-01-12T23:27:53.099Z","etag":null,"topics":["api","aws","docker","lambda","pdm","pytorch","sam"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ae9is.png","metadata":{"files":{"readme":"README.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}},"created_at":"2024-02-25T05:58:11.000Z","updated_at":"2024-02-25T12:47:54.000Z","dependencies_parsed_at":"2024-03-15T18:09:39.240Z","dependency_job_id":null,"html_url":"https://github.com/ae9is/py-lambda-docker","commit_stats":null,"previous_names":["ae9is/py-lambda-docker"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ae9is%2Fpy-lambda-docker","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ae9is%2Fpy-lambda-docker/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ae9is%2Fpy-lambda-docker/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ae9is%2Fpy-lambda-docker/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ae9is","download_url":"https://codeload.github.com/ae9is/py-lambda-docker/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":241494180,"owners_count":19971871,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","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":["api","aws","docker","lambda","pdm","pytorch","sam"],"created_at":"2024-11-13T14:03:05.006Z","updated_at":"2025-12-31T01:06:05.364Z","avatar_url":"https://github.com/ae9is.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# py-lambda-docker\n\nBoilerplate example for setting up a serverless api using AWS Lambda via SAM.\n\nLambdas which run off ECR-uploaded Docker images are needed for heavier weight dependencies like Pytorch.\n\nFor longer jobs, API Gateway has a request limit of 30 seconds for HTTP/REST APIs (which can be worked around via WebSocket APIs). Here Lambda Function URLs are used instead, which support timeouts of up to 15 minutes.\n\n## Setup\n\n### Environment variables\n\nSetup loading .env variables: https://direnv.net/\n\n```bash\ndirenv allow\n```\n\n### Python\n\nUses Python 3.11. To easily switch between versions of python, consider setting up [pyenv](https://github.com/pyenv/pyenv).\n\n[PDM](https://github.com/pdm-project/pdm) is used for proper dependency resolution and convenience scripts.\n\n```bash\npip install pipx\npipx install pdm\n```\n\nPre-commit is used for some commit hooks:\n```bash\npip install pre-commit\npre-commit install\n```\n\n### IAM Identity Center (SSO)\n\n1. Enable IAM Identity Center following: https://aws.amazon.com/iam/identity-center/\n1. Add user `admin`\n1. Add group `Admins` to Groups\n1. Add `admin` to `Admins`\n1. Add a permission set `AdministratorAccess` based on the `AdministratorAccess` AWS managed policy\n1. Assign the permission set to the `Admins` group under `AWS accounts → Assign users or groups`\n\n### AWS CLI\n1. Install AWS CLI\n\n    ```bash\n    curl \"https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip\" -o \"awscliv2.zip\"\n    unzip awscliv2.zip\n    sudo ./aws/install\n    # or update:\n    $ sudo ./aws/install --bin-dir /usr/local/bin --install-dir /usr/local/aws-cli --update\n    ```\n\n    (ref: https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)\n\n1. Configure CLI session and login\n\n    ```bash\n    aws configure sso\n    # enter info...\n    aws sso login --sso-session admin\n    ```\n\n1. Check the resulting config at `~/.aws/config` and make sure it matches what you expect, for ex:\n\n    ```\n    [profile admin]\n    region = us-east-1\n    sso_session = admin\n    sso_account_id = 123456789012\n    sso_role_name = AdministratorAccess\n\n    [sso-session admin]\n    sso_region = us-east-1\n    sso_start_url = https://my-sso-portal.awsapps.com/start\n    sso_registration_scopes = sso:account:access\n    ```\n\n    (ref: https://docs.aws.amazon.com/cli/latest/userguide/sso-configure-profile-token.html)\n\n## Install\n\n```bash\npdm install-all\n```\n\n## Build\n\nThe pdm script also lints the syntax of the `template.yaml` file.\n\n```bash\npdm sam-build\n```\n\n## Deploy\n\nMake sure `AWS_REGION` and `AWS_ACCOUNT_ID` are set in `.env` environment variables. These are needed to login Docker to ECR.\n\nSign into AWS SSO using a user that can deploy:\n\n```bash\naws sso login --profile admin\n```\n\nLogin Docker to AWS ECR:\n```bash\npdm docker-login\n```\n\nThis run script triggers a build and also outputs the deployed Lambda Function URL for convenience:\n\n```bash\npdm sam-deploy\n```\n\n## Test\n\nUse a tool that supports AWS signature v4 to test, for example postman (https://www.postman.com/) or curl (https://stackoverflow.com/a/68456301).\n\n### Postman\n\n1. In Postman, select AWS Signature under the Authorization tab.\n1. Add postman environment variables for the parameters:\n   - AccessKey: {{access_key}}\n   - SecretKey: {{secret_key}}\n   - AWS Region: {{region}}\n   - Service Name: {{service}}\n   - Session Token: {{session_token}}\n1. Create and edit the variables in an environment:\n   ```\n   (variable)    (type)   (initial value)\n   access_key    secret   ''\n   secret_key    secret   ''\n   region        default  us-east-1\n   service       default  lambda\n   session_token secret   ''\n   ```\n1. For future sessions you need to copy in the credentials into \"current value\" for the secret variables.\n\n### Automated\n\nStart up local api endpoint (see [SAM local limitations](#sam-local-limitations)):\n```bash\npdm local\n# Separate terminal tab\npdm fwd\n```\n\nThen:\n```bash\npdm test\n```\n\n## Run (local api)\n\nDifferent pdm scripts exist for testing the Lambda endpoints locally:\n\n- sam-local: local Lambda emulation\n- fwd-sam-local: start up an endpoint that just forwards api requests to sam local\n\n### Authentication\n\nLocal Lambda authentication is handled automatically--you need to setup and login to AWS SSO to use sam local.\n\n### SAM local limitations\n\nSAM local does not support running an api for Lambda Function URLs automatically.\nref: https://github.com/aws/aws-sam-cli/issues/4299\n\nTo run local api conveniently (shorter url, GET rather than POST), there is a Flask app to interface with SAM local.\n\nCheck which methods are implemented at `localapi/app.py` (i.e. GET, POST, ...).\n\n```bash\n# Convenience script to sam local command\npdm local\n# Convenience script to run flask forwarder\npdm fwd\n```\n\nThen you can call for example: `curl http://localhost:5000/`\n\nAlternatively, just run sam local (or `pdm local`) and then:\n\n```bash\ncurl -XPOST http://localhost:3001/2015-03-31/functions/{lambda_function_name}/invocations -d '{\"payload\":\"value\"}'\n```\n\nNote that only POST and setting request body seems to be supported.\n\n\u0026nbsp;\n\n---\n\n# Default SAM documentation\n\nThis project contains source code and supporting files for a serverless application that you can deploy with the SAM CLI. It includes the following files and folders.\n\n- hello_world - Code for the application's Lambda function and Project Dockerfile.\n- events - Invocation events that you can use to invoke the function.\n- tests - Unit tests for the application code. \n- template.yaml - A template that defines the application's AWS resources.\n\nThe application uses several AWS resources, including Lambda functions and an API Gateway API. These resources are defined in the `template.yaml` file in this project. You can update the template to add AWS resources through the same deployment process that updates your application code.\n\n## Deploy the sample application\n\nThe Serverless Application Model Command Line Interface (SAM CLI) is an extension of the AWS CLI that adds functionality for building and testing Lambda applications. It uses Docker to run your functions in an Amazon Linux environment that matches Lambda. It can also emulate your application's build environment and API.\n\nTo use the SAM CLI, you need the following tools.\n\n* SAM CLI - [Install the SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html)\n* Docker - [Install Docker community edition](https://hub.docker.com/search/?type=edition\u0026offering=community)\n\nYou may need the following for local testing.\n* [Python 3 installed](https://www.python.org/downloads/)\n\nTo build and deploy your application for the first time, run the following in your shell:\n\n```bash\nsam build\nsam deploy --guided\n```\n\nThe first command will build a docker image from a Dockerfile and then copy the source of your application inside the Docker image. The second command will package and deploy your application to AWS, with a series of prompts:\n\n* **Stack Name**: The name of the stack to deploy to CloudFormation. This should be unique to your account and region, and a good starting point would be something matching your project name.\n* **AWS Region**: The AWS region you want to deploy your app to.\n* **Confirm changes before deploy**: If set to yes, any change sets will be shown to you before execution for manual review. If set to no, the AWS SAM CLI will automatically deploy application changes.\n* **Allow SAM CLI IAM role creation**: Many AWS SAM templates, including this example, create AWS IAM roles required for the AWS Lambda function(s) included to access AWS services. By default, these are scoped down to minimum required permissions. To deploy an AWS CloudFormation stack which creates or modifies IAM roles, the `CAPABILITY_IAM` value for `capabilities` must be provided. If permission isn't provided through this prompt, to deploy this example you must explicitly pass `--capabilities CAPABILITY_IAM` to the `sam deploy` command.\n* **Save arguments to samconfig.toml**: If set to yes, your choices will be saved to a configuration file inside the project, so that in the future you can just re-run `sam deploy` without parameters to deploy changes to your application.\n\nYou can find your API Gateway Endpoint URL in the output values displayed after deployment.\n\n## Use the SAM CLI to build and test locally\n\nBuild your application with the `sam build` command.\n\n```bash\nsam-app$ sam build\n```\n\nThe SAM CLI builds a docker image from a Dockerfile and then installs dependencies defined in `hello_world/requirements.txt` inside the docker image. The processed template file is saved in the `.aws-sam/build` folder.\n\nTest a single function by invoking it directly with a test event. An event is a JSON document that represents the input that the function receives from the event source. Test events are included in the `events` folder in this project.\n\nRun functions locally and invoke them with the `sam local invoke` command.\n\n```bash\nsam-app$ sam local invoke HelloWorldFunction --event events/event.json\n```\n\nThe SAM CLI can also emulate your application's API. Use the `sam local start-api` to run the API locally on port 3000.\n\n```bash\nsam-app$ sam local start-api\nsam-app$ curl http://localhost:3000/\n```\n\nThe SAM CLI reads the application template to determine the API's routes and the functions that they invoke. The `Events` property on each function's definition includes the route and method for each path.\n\n```yaml\n      Events:\n        HelloWorld:\n          Type: Api\n          Properties:\n            Path: /hello\n            Method: get\n```\n\n## Add a resource to your application\nThe application template uses AWS Serverless Application Model (AWS SAM) to define application resources. AWS SAM is an extension of AWS CloudFormation with a simpler syntax for configuring common serverless application resources such as functions, triggers, and APIs. For resources not included in [the SAM specification](https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md), you can use standard [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html) resource types.\n\n## Fetch, tail, and filter Lambda function logs\n\nTo simplify troubleshooting, SAM CLI has a command called `sam logs`. `sam logs` lets you fetch logs generated by your deployed Lambda function from the command line. In addition to printing the logs on the terminal, this command has several nifty features to help you quickly find the bug.\n\n`NOTE`: This command works for all AWS Lambda functions; not just the ones you deploy using SAM.\n\n```bash\nsam-app$ sam logs -n HelloWorldFunction --stack-name \"sam-app\" --tail\n```\n\nYou can find more information and examples about filtering Lambda function logs in the [SAM CLI Documentation](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-logging.html).\n\n## Unit tests\n\nTests are defined in the `tests` folder in this project. Use PIP to install the [pytest](https://docs.pytest.org/en/latest/) and run unit tests from your local machine.\n\n```bash\nsam-app$ pip install pytest pytest-mock --user\nsam-app$ python -m pytest tests/ -v\n```\n\n## Cleanup\n\nTo delete the sample application that you created, use the AWS CLI. Assuming you used your project name for the stack name, you can run the following:\n\n```bash\nsam delete --stack-name \"sam-app\"\n```\n\n## Resources\n\nSee the [AWS SAM developer guide](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/what-is-sam.html) for an introduction to SAM specification, the SAM CLI, and serverless application concepts.\n\nNext, you can use AWS Serverless Application Repository to deploy ready to use Apps that go beyond hello world samples and learn how authors developed their applications: [AWS Serverless Application Repository main page](https://aws.amazon.com/serverless/serverlessrepo/)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fae9is%2Fpy-lambda-docker","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fae9is%2Fpy-lambda-docker","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fae9is%2Fpy-lambda-docker/lists"}