Going Serverless on AWS For The .NET Developer: How To Easily Get Started
Tags: aws, serverless, dotnet
Published: 2021-04-19 04:13:30

[AWS Lambda's](https://www.rahulpnath.com/blog/aws-lambda-net-core/) are the stepping stones to building a Serverless application in AWS.

A Serverless Application in AWS is a combination of Lambda functions, event sources, and other resources that work together to perform tasks. It is more than just a Lambda function; it can include additional resources such as APIs, databases, and event source mappings. 

> *The AWS Serverless Application template is the AWS Toolkit for Visual Studio implementation of the [AWS Serverless Application Model](https://aws.amazon.com/serverless/sam/) (AWS SAM). Using this project type, you can develop a collection of AWS Lambda functions and deploy them with any necessary AWS resources as a whole application, using AWS CloudFormation to orchestrate the deployment.*

Now that's a lot of jargon in one line. Let's understand each of them better.

{% youtube iLo8svHzD_g %}

In this post, let's learn how to build an AWS Serverless application using the Serverless Application Template as part of the AWS Toolkit. We will see how we can deploy one or more Lambda functions using the AWS SAM and also use it to deploy a Lambda-driven API Gateway application backed by a DynamoDB database. 

## Creating an AWS Serverless Application

The [AWS Toolkit for Visual Studio](https://aws.amazon.com/visualstudio/) comes with a built-in template to create a Serverless Application.

To create a new application, choose the '*AWS Serverless Application (.NET Core - C#)*' option from the template list when creating a new project.

![AWS Serverless templates in Visual Studio create project](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tav8tcidhyxdtatml8fj.jpg)

Select the '*Empty Serverless Application*' blueprint to create a Serverless application with just one function.

As shown below, it contains the same set of files as we saw in the [previous post on getting started with AWS Lambda](https://www.rahulpnath.com/blog/aws-lambda-net-core/) with the addition of one new file `serverless.template` ;which is the AWS SAM template file. 

![AWS Serverless Application Empty blueprint application default items](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cgi6xlp0rzbzguae9kpn.jpg)

### AWS Serverless Application Model (SAM)

The [AWS Serverless Application Model](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/what-is-sam.html) (AWS SAM) is an open-source framework that you can use to build serverless applications on AWS. It allows us to define the AWS resources as code - in other words, it's [Infrastructure as Code (IaC)](https://en.wikipedia.org/wiki/Infrastructure_as_code).

AWS SAM consists of the following components

- Template specification → Provides a clean and straightforward way to describe the required infrastructure
- Command Line Interface (CLI) → Commands to build and deploy the resources to AWS

*AWS SAM templates are an extension of AWS CloudFormation templates*, with some additional components make them easier to work with.

### AWS CloudFormation

[AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) simplifies Infrastructure management, quickly replicate infrastructure and easily control and track infrastructure changes.

> *AWS CloudFormation is a service that helps you model and set up your Amazon Web Services resources so that you can spend less time managing those resources and more time focusing on your applications that run in AWS.*

When using CloudFormation, you normally work with [Templates and Stacks.](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-whatis-concepts.html)

- ***Templates*** are YAML or JSON files that act as blueprints for building AWS resources. It has a well-defined [structure and schema defined.](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-anatomy.html)

- A group of related resources forms a single unit called a ***Stack.*** You manage resources by basically managing stacks.

### serverless.template File

The *serverless.template* file is used to define the Serverless Application. It can contain different sections of which *Transform* and *Resources* sections are required.

The `Transform` element in the template file indicates this file to contain AWS SAM syntax, which will be [transformed into AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/transform-aws-serverless.html) compliant format.

```json
{
  "AWSTemplateFormatVersion": "2010-09-09",
  "Transform": "AWS::Serverless-2016-10-31",
  "Description": "An AWS Serverless Application.",
  "Resources": {
    "Get": {
      "Type": "AWS::Serverless::Function",
      "Properties": {
        "Handler": "empty::empty.Functions::Get",
        "Runtime": "dotnetcore3.1",
        "CodeUri": "",
        "MemorySize": 256,
        "Timeout": 30,
        "Role": null,
        "Policies": [
          "AWSLambdaBasicExecutionRole"
        ],
        "Events": {
          "RootGet": {
            "Type": "Api",
            "Properties": {
              "Path": "/",
              "Method": "GET"
            }
          }
        }
      }
    }
  },
  "Outputs": {
    "ApiURL": {
      "Description": "API endpoint URL for Prod environment",
      "Value": {
        "Fn::Sub": "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/"
      }
    }
  }
}
```

The [AWS::Serverless::Function](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-resource-function.html) creates an AWS Lambda function, an IAM Role and event source mappings that trigger the function. It supports various properties as used above to configure the AWS Lambda.

The above scenario defines the Lambda with *AWSLambdaBasicExecutionRole* role and triggered by an API Gateway using the **HTTP GET** method.

{% youtube IHIJFVUQyFY %}

The Lambda maps to the `Get` method within the `Functions` class. 

```csharp
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]
namespace empty
{
    public class Functions
    {
        public APIGatewayProxyResponse Get(
            APIGatewayProxyRequest request, ILambdaContext context)
        {
            context.Logger.LogLine("Get Request\n");

            var response = new APIGatewayProxyResponse
            {
                StatusCode = (int)HttpStatusCode.OK,
                Body = "Hello AWS Serverless",
                Headers = new Dictionary<string, string> { { "Content-Type", "text/plain" } }
            };

            return response;
        }
    }
}
```

The function takes in an `APIGatewayProxyResponse` and returns `APIGatewayProxyResponse` since API Gateway triggers it. It simply returns a hard-coded text.

To add another Lambda function, we need to create a new function endpoint in the code and add another resource in the `serverless.template` file.

## Deploying To AWS

The easiest way to publish the AWS Lambda function to AWS infrastructure is to right-click on the project and select the 'Publish To AWS Lambda...' option. It prompts up a dialog to choose the AWS profile, region, and CloudFormation settings.

*In real-life projects, I set up a build deploy pipeline to automate this, which we will see in a different post.*

[CloudFormation first uploads the package to deploy](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-whatis-howdoesitwork.html) and the template to an S3 bucket and then deploys the application resources from there. The CloudFormation settings take this as a parameter.

It also requires the Stack Name as a parameter, to which all the resources are deployed.

![Publish AWS Serverless Application in Visual Studio](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ccwv351554cpkb408fmo.jpg)

Once complete, it automatically opens the CloudFormation Stack view within Visual Studio. If not, you can manually do this from the *AWS Explorer* (that is part of the AWS Toolkit), available from View → AWS Explorer. Navigate to AWS CloudFormation and select the stack name you just deployed.

The *AWS Serverless URL* is the API Gateway URL where the Lambda function is exposed. The *ApiURL* in the *Outputs* section of the template file populates this URL.

![Published stack details of AWS Serverless application in Visual Studio](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/upfuentddmr40s8n48kf.jpg)

You can also see the Stack's details, the associated resources, and various other information under the [Stacks in AWS Console](https://ap-southeast-2.console.aws.amazon.com/cloudformation/home) under the appropriate region. It lists all the resources part of the Stack and allows navigating to each of them.

![AWS Console Resources under Stack](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3zffcpo2cc3ycv8mp2ud.jpg)

Navigating the API URL, it returns the hardcoded message from the AWS lambda → "*Hello AWS Serverless*".

### CloudFormation and S3 Bucket

Each time the application is published, the template and the associated published application package are uploaded to the selected S3 bucket.  You can navigate to the S3 bucket to view the files.

![CloudFormation associated S3 bucket](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wcrzwek7k4i5aqxd6fb5.jpg)

## Web API using Azure Lambda, API Gateway, and DynamoDB

To create a more complex AWS Serverless applications that use a DynamoDB table to store and retrieve data using AWS Lambda's and API Gateway, you can select the 'Blog API using DynamoDB' as the blueprint.

![AWS Serverless Application Template Blueprint, Blog API using DynamoDB](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/prxj29mto6xjxepqo506.jpg)

It scaffolds a template with 4 API endpoints to `GetBlogs`, `GetBlog`, `AddBlog`, and `RemoveBlog` items from a DynamoDB table.

{% youtube BbUmLRaxZG8 %}

As with the Empty template we created earlier, this one has a `serverless.template` file which defines all the resources (AWS Lambda, DynamoDB, etc.) required for this application. 

It also has additional `Parameters` and `Condition` defined in the template to decide on whether to create the DynamoDB table or not. Because of this, it prompts an additional dialog to enter the parameters on publishing.

![AWS Serverless Publish Template Parameters dialog](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f0vfmb1jprc1uumvtlmt.jpg)

Once published, we can use the API URL to interact with the Blog Items in the DynamoDB table. You can use curl or [Postman](https://www.postman.com/) etc. to make the `PUT` request to add items to it. 

```bash
curl --location --request PUT '<API URL>' \
--header 'Content-Type: application/json' \
--data-raw '{"Name": "AWS Serverless", "Content": "This is a test blog"}'
```

The other API endpoints can retrieve and delete items if required. 

We have a fully functional API endpoint to manage Blog items backed by the DynamoDB database. 

I hope this helps you get started with building AWS Serverless application for AWS and understand more about its various building blocks. 

Feel free to drop in the comments or [send a tweet](https://twitter.com/rahulpnath) if you have any comments or questions.

**References**

- [What is AWS SAM](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/what-is-sam.html)?
- [What is AWS CloudFormation?](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html)
- [AWS SAM Template anatomy](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-specification-template-anatomy.html)