Serverless Application Model 101
Tags: serverless, cloud, aws, beginners
Published: 2023-06-23 23:17:01

SAM is an OSS framework developed by AWS that simplifies the deployment and management of serverless applications (Applications with API gateway, Lambdas, DynamoDB and Event oriented). SAM extends AWS CloudFormation to provide a simplified syntax specifically designed for serverless resources such as triggers and listeners to events or even policy templates ready to use.

```yaml
  CommunityBuilderFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: first_article/
      Handler: app.lambda_handler
      FunctionName: get-first-article
      Events:
        ArticleEvent:
          Type: Api
          Properties:
            Path: /v1/articles
            Method: post
            RestApiId: !Ref ApiDeployment

```

## Benefits:

- **Simplified Serverless Application Development:** with AWS SAM, developers can easily define the application's resources, events, and dependencies in a declarative template, making it straightforward to understand and maintain the application's architecture.
- **Local Development and Testing:** one of the challenges in serverless development is the lack of a local development environment. AWS SAM addresses this challenge by providing a local development and testing experience. Developers can use the AWS SAM CLI (Command Line Interface) to run their serverless applications locally, simulating the AWS Lambda execution environment. **`Bring the developer to the cloud`**
- **Deployment and Infrastructure as Code:** AWS SAM leverages AWS CloudFormation to provide infrastructure as code capabilities for serverless applications.
- **Built-in Best Practices:** AWS SAM also includes automatic resource creation, such as IAM roles and policies, reducing the manual effort required to set up these resources, you have some predefined policies and can be as granular as you want

```yaml
Policies:
   - DynamoDBCrudPolicy:
       TableName: CommunityTable
```

- **Simplified CI/CD:** You can use SAM CLI to integrate with popular CI/CD providers such as GitHub Actions, CodePipeline, and GitLab. Run `sam pipeline init --bootstrap` and follow the configurations to create the required resources and a default template file specific to the provider. You can then optimize and adjust it to tailor to your specific needs.

## Initialise a project

`sam init`

- SAM CLI - [[Install the SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html)]
- Python - [[Python 3](https://www.python.org/downloads/)]
- Docker - [[Install Docker community edition](https://hub.docker.com/search/?type=edition&offering=community)]To build and deploy your application for the first time, run the following in your shell:

To build and deploy your application for the first time, run the following in your shell:

- `sam build --use-container`
- `sam deploy --guided`

The first command will build the source of your application. 

The second command will package and deploy your application to AWS, with a series of prompts:

- **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.
- **AWS Region:** The AWS region you want to deploy your app to.
- **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.
- **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.
- **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.

## Use the SAM CLI to build and test locally

Build your application with the `sam build --use-container` command.

The SAM CLI installs dependencies defined in `<lambda>/requirements.txt`, creates a deployment package, and saves it in the `.aws-sam/build` folder.

Test 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.

Run functions locally and invoke them with the `sam local invoke` command.

`sam local invoke HelloWorldFunction --event events/event.json`

The SAM CLI can also emulate your application's API. Use the `sam local start-api` to run the API locally on port 3000. Then execute the call using `curl http://localhost:3000/`

The 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.


## Create a new resource to your application

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 SAM you can use CloudFormation.


![Builders](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ueybjao1kigb39lr1av6.png)


## Fetch Lambda logs

To simplify troubleshooting, SAM CLI has a command called `sam logs`. it 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 features to help you quickly find the bug.

`sam logs -n HelloWorldFunction --stack-name builders-stack --tail`

## Cleanup

To 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: `aws cloudformation delete-stack --stack-name builders-stack`

## Conclusion

AWS Serverless Application Model  is a powerful tool that can simplify the development and management of serverless applications. 

It provides developers with built-in best practices, local development and testing capabilities, deployment and infrastructure as code, and simplified CI/CD. By using SAM, developers can focus on writing code and delivering value to their customers, instead of worrying about infrastructure and deployment.