Create the Serverless Microservice with AWS Lambda and API Gateway in .Net Core
In this post, I will explain how you can create a simple microservice in .Net Core, deploy that to the serverless infrastructure of Amazon Web Services (AWS) called Lambda and expose that microservice to the internet using API Gateway.
To learn about the microservice and API Gateway please see my post Build your own API Gateway in Microservice based Architecture.
See my similar post on Azure: Create the Serverless Microservice with Azure Function and HTTP Trigger in .Net
Lambda is the AWS compute service where you can deploy and run the code without provisioning or managing servers.
We will create a simple microservice which returns the customer info on the HTTP Get request from the customer details stored in the DynamoDB database.
DynamoDB is the fast and reliable No SQL database of Amazon Web Sevices.
See the complete source code on Github.
To start with, you need following tools:
Start Visual Studio and click new project.
In the New Project screen, select AWS Lambda Project (.Net Core). Enter the project name CustomerServiceLambda, enter the location where you want to create a project and click OK.
In the Select Blueprint screen, select Empty Function and click Finish.
CustomerServiceLambda project will be created with the following directory structure:
Add the following Nugget packages in your project:
Open the Function.cs file, you will see following default code:
using Amazon.Lambda.Core;
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))]
namespace CustomerServiceLambda
{
public class Function
{
public string FunctionHandler(string input, ILambdaContext context)
{
return input?.ToUpper();
}
}
}
Replace the default FunctionHandler with the following code:
public APIGatewayProxyResponse FunctionHandler(APIGatewayProxyRequest request, ILambdaContext context)
{
string customerId = string.Empty;
if (request.QueryStringParameters != null && request.QueryStringParameters.ContainsKey("id"))
{
customerId = request?.QueryStringParameters["id"];
}
var customer = GetCustomer(customerId);
return new APIGatewayProxyResponse
{
StatusCode = 200,
Body = JsonConvert.SerializeObject(customer)
};
}
Next, add the GetCustomer method which will retrieve the customer from the DynamoDB database based on the customer id passed in the request:
public Customer GetCustomer(string id)
{
var dynamoDbClient = new AmazonDynamoDBClient();
string tableName = "Customer";
var request = new QueryRequest
{
TableName = tableName,
KeyConditionExpression = "Id = :v_Id",
ExpressionAttributeValues = new Dictionary<string, AttributeValue> {
{":v_Id", new AttributeValue { S = id }}}
};
var response = dynamoDbClient.QueryAsync(request).Result;
var item = response.Items.First();
var customerName = item["CustomerName"].S;
return new Customer { Id = id, CustomerName = customerName };
}
Next, add the Customer class.
public class Customer
{
public string Id { get; set; }
public string CustomerName { get; set; }
}
Next, publish the CustomerServiceLambda to AWS.
Before you can publish to the AWS, you need to create the Account Profile under AWS Explorer in Visual Studio.
Click View and click AWS Explorer.
Recommended by LinkedIn
Click the New Account Profile icon.
You would need the Access Key ID and Secret Access Key which you get when you create the user account in IAM in AWS.
Once you have the account profile setup and logged on to the AWS Explorer, right click on your project and click Publish to AWS Lambda…
In the Function Name enter CustomerServiceLambda, leave the defaults and click Next.
Select the Role Name and click Upload. If you don’t have the role created, login to the AWS console and create a new role under IAM. Assign the appropriate permission to the role to execute the Lambda function.
Once publish is successful, you will see the CustomerServiceLambda function under the Lambda screen under your account in AWS console.
Before we setup the API Gateway, we need to create the Customer table in DynamoDB and populate with some records.
In the AWS console, click DynamoDB under services click Create table. Create the Customer table with the attribute customerName.
Next, add some records in the Customer table. In the AWS console, click DynamoDB and click Customer table under the list of tables, click Items tab, and click Create Item. Add few records.
Next, we will configure the API Gateway.
In AWS console, under services click Lambda. In the list of functions click CustomerServiceLambda function we just created.
In the next screen that appears, click Triggers tab.
Click Add trigger.
Click on the blank area before the green arrow, you will see the list of triggers appear. Click API Gateway.
In the API name field enter CustomerService, enter or select the Deployment stage. In the security, you specify the access permission to the CustomerService API. You have three options here:
For the simplicity, we will select Open and click Submit button. You will see the API Gateway trigger will be setup.
API is now ready to be called. To get the API URL, click the Details arrow and copy the Invoke URL. Paste the URL in the browser address bar and append the customer ID in query string id=4.
https://xs87v6rwfg.execute-api.ap-southeast-2.amazonaws.com/prod/CustomerServiceLambda?id=4
You will see the JSON response in your browser window:
{
"Id":"4",
"CustomerName":"Muhammad Irfan"
}
You can define the friendly URL of your API following the steps here.
See the complete source code on Github.