DEV Community

loading...
Cover image for Going Serverless on AWS For The .NET Developer: How To Easily Get Started

Going Serverless on AWS For The .NET Developer: How To Easily Get Started

rahulpnath profile image Rahul Nath Originally published at rahulpnath.com ・6 min read

AWS Lambda's 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 (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.

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

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 with the addition of one new file serverless.template ;which is the AWS SAM template file.

AWS Serverless Application Empty blueprint application default items

AWS Serverless Application Model (SAM)

The AWS Serverless Application Model (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).

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

  • Templates are YAML or JSON files that act as blueprints for building AWS resources. It has a well-defined structure and schema defined.

  • 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 compliant format.

{
  "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/"
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

The AWS::Serverless::Function 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.

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

[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;
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

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

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

You can also see the Stack's details, the associated resources, and various other information under the Stacks in AWS Console 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

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

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

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

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

Once published, we can use the API URL to interact with the Blog Items in the DynamoDB table. You can use curl or Postman etc. to make the PUT request to add items to it.

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

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 if you have any comments or questions.

References

Discussion (0)

pic
Editor guide