Single Microservice Expose HTTPS methods with Lambda Function URL

In this article, we are going to do Hands-on Lab: Single Microservice Expose https methods with AWS Lambda Function URL.

Single Calculator Microservice Expose https methods with Lambda Function Url

By the end of the article, we will create a Single Calculator Microservice and expose APIs with using AWS Lambda Function Url.

I have just published a new course — AWS Lambda & Serverless — Developer Guide with Hands-on Labs.

AWS Lambda Function URLs: Built-in HTTPS Endpoints

Basically Function URLs is on of the latest brand new feature of AWS Lambdas. This feature comes because of the enterprise company requirements. Lambda Function URLs is lets you add HTTPS endpoints to any Lambda function.

AWS Lambda Function URLs

Hands-on Lab: Calculator Project

Basically Calculator project as the name suggested, calculate given operator and the numbers and return back to result.

Single Calculator Microservice Expose https methods with Lambda Function Url

We will access Event Parameters into Lambda Function. At first, let’s design incoming event.json object which trigger to lambda function:

{
“a”: 2,
“b”: 5,
“op”: “+”
}

So this event will trigger Lambda function, that means we will develop our function accommodate with these a, b and op parameters. So at that stage, please create a lambda function and active Lambda Function URL.

Since we have invoke our function with function-url our request payload will be different. In order to check incoming request, let me send POST request to other lambda function. To test other HTTP requests, such as a POST request, you can use a tool such as curl or postman.

curl -v -X POST \
https://abcdefg.lambda-url.us-east-1.on.aws/?message=HelloWorld' \
-H ‘content-type: application/json’ \
-d ‘{ “example”: “test” }’

But I would like to choose POSTMAN:

 Header content — -H ‘content-type: application/json’ \
payload
body -raw — json
{
“a”: 2,
“b”: 5,
“op”: “+”
}

Now we can check AWS CloudWatch Logs for Lambda Function URL:

EVENT: 
{
“version”: “2.0”,
“routeKey”: “$default”,
“rawPath”: “/”,
“rawQueryString”: “”,
“headers”: {
“content-length”: “45”,
“x-amzn-trace-id”: “Root=1–628b7fb8–6f1845770acba10d5d45e863”,
“x-forwarded-proto”: “https”,
“postman-token”: “f76478ee-e7d8–462b-8b80–792d2574f432”,
“host”: “xxxxx.lambda-url.us-east-2.on.aws”,
“x-forwarded-port”: “443”,
“content-type”: “application/json”,
“x-forwarded-for”: “213.74.44.192”,
“accept-encoding”: “gzip, deflate, br”,
“accept”: “*/*”,
“user-agent”: “PostmanRuntime/7.29.0”
},
“requestContext”: {
“accountId”: “anonymous”,
“apiId”: “xxxxxx”,
“domainName”: “xxxx.lambda-url.us-east-2.on.aws”,
“domainPrefix”: “xxxxx”,
“http”: {
“method”: “POST”,
“path”: “/”,
“protocol”: “HTTP/1.1”,
“sourceIp”: “213.74.44.192”,
“userAgent”: “PostmanRuntime/7.29.0”
},
“requestId”: “xxxxx–5130–4339-abc5-e7a9785eec2b”,
“routeKey”: “$default”,
“stage”: “$default”,
“time”: “23/May/2022:12:36:08 +0000”,
“timeEpoch”: xxxxx
},
“body”: “{\r\n \”a\”: 2,\r\n \”b\”: 5,\r\n \”op\”: \”+\”\r\n}”,
“isBase64Encoded”: false
}

See that httpMethod: POST and payload is in the body attribute:

“body”: “{\r\n \”a\”: 2,\r\n \”b\”: 5,\r\n \”op\”: \”+\”\r\n}”,

So we should parse this body json object and perform our business logic. Now we are ready to develop our hands-on lab.

Single Calculator Microservice Expose https methods with Lambda Function Url

Now we can breakdown with step-by-step todo-list:

  1. Develop AWS Lambda Function Code
  2. Zip Function Code
  3. Create AWS Lambda Function with AWS CLI
  4. Create Lambda Function URL Config with AWS CLI
  5. Invoke AWs Lambda Function with AWS CLI

1- Develop AWS Lambda Function Code

We will start with developing index.js handler method of our hands-on Greeting project. We will use NodeJS as a runtime of AWS Lambda function. So please create index.js file and start developing into this file with using VSCODE editor.

exports.handler = async (event) => {
console.log("event:", JSON.stringify(event, undefined, 2));
let payload = JSON.parse(event.body);
let result = 0;
try {
if (payload.a === undefined || payload.b === undefined || payload.op === undefined) {
throw new Error(`event should exist a-b-op: "${event}"`);
}

switch(payload.op) {
case "+":
result = payload.a + payload.b;
break;
case "-":
result = payload.a - payload.b;
break;
case "*":
result = payload.a * payload.b;
break;
case "/":
result = payload.b === 0 ? NaN : payload.a / payload.b;
break;
}
console.log('Result is : ', result);
} catch (error) {
console.error(error)
return {
statusCode: 400,
body: `Cannot process event: ${error}`,
}
}
return {
statusCode: 200, // default value
body: JSON.stringify({
processed: true,
result: result
}),
};
};

We basically expect an event that triggers to lambda function and includes a, b and op attributes. With these attributes, we will do our business logic and calculate operation and return back to result number as per the incoming event parameters.

2- Zip Function Code

The second step is zip compress function code in order to deploy on AWS environment. We can use zip or compress command as per operating system:

mac
zip function.zip index.js
windows
Compress-Archive index.js function.zip
manuel
go to index.js
Right click index.js
Send to -> Compressed (zip) folder

3- Create AWS Lambda Function with AWS CLI

Now we are ready to create our AWS Lambda function with using deployable zip file. But before that we should create or get an execution role which exists AWS Lambda Basic Execution permissions.

Get Role:
aws iam get-role — role-name lambda-exResponse:
{
“Role”: {
“Path”: “/”,
“RoleName”: “lambda-ex”,
“Arn”: “arn:aws:iam::xxxxxxx:role/lambda-ex”,

Get the Arn information of the role and start to create-function command. AWS Lambda Create function with using execution role and CLI commands:

windows
aws lambda create-function `
— function-name calculator `
— runtime nodejs14.x `
— zip-file fileb://function.zip `
— handler index.handler `
— role arn:aws:iam::xxxxx:role/lambda-exResponse:
Created :
{
“FunctionName”: “calculator”,
“FunctionArn”: “arn:aws:lambda:us-east-2:xxxxxx:calculator”

We use multi-line char in our CLI commands and it can differs as per operating systems.

4- Create Function URL Config with AWS CLI

Now we can create function URL Config to our lambda function in order to expose HTTPs endpoint to make it single exposed microservice. Run below CLI Commands:

aws lambda create-function-url-config `
— function-name calculator `
— auth-type NONE
Response:
{
“FunctionUrl”: “https://xxxxxxxx.lambda-url.us-east-2.on.aws/",
“FunctionArn”: “arn:aws:lambda:us-east-2:xxxxx:function:calculator”,
“AuthType”: “NONE”,
“CreationTime”: “2022–05–23T12:56:21.663701Z”
}

As you can see that we have exposed APIs with using Lambda function URL that you can also check from AWS Management Console of Lambda function.

5- Invoke AWS Lambda Function with AWS CLI

Finally, we are ready to invoke our newly created AWS Lambda function with synchronously. First of all, we should create event.json file which will be an event to trigger lambda function.

POSTMAN
Header content — -H ‘content-type: application/json’ \
payload
body -raw — json
{
“a”: 2,
“b”: 5,
“op”: “+”
}
Send request
POST
https://xxxx.lambda-url.us-east-2.on.aws/
Response:
{
"processed": true,
"result": 7
}

If you got Message: Forbidden exception that means you don’t have permission to invoke this function. Go to Console — Function — Configuration — Function URL — Resource-based policy- Add Permission- Policy statement = Function Url

As you can see that we have successfully invoke and get response from our Calculator lambda function. You can also check CloudWatch Logs for execution logs.

Delete Function

Last step we should delete our function. Please follow below CLI command to delete and verify functions on your AWS cloud:

Clean up resources
aws lambda delete-function — function-name greeting
aws lambda list-functions
aws lambda get-function — function-name my-function

As you can see that, we pass event json objects and read from lambda function.

Step by Step Design AWS Architectures w/ Course

I have just published a new course — AWS Lambda & Serverless — Developer Guide with Hands-on Labs.

In this course, we will learn almost all the AWS Serverless Services with all aspects. We are going to build serverless applications with using AWS Lambda, Amazon API Gateway, Amazon DynamoDB, Amazon Cognito, Amazon S3, Amazon SNS, Amazon SQS, Amazon EventBridge, AWS Step Functions, DynamoDB and Kinesis Streams. This course will be 100% hands-on, and you will be developing a real-world application with hands-on labs together and step by step.

Source Code

Get the Source Code from Serverless Microservices GitHub — Clone or fork this repository, if you like don’t forget the star. If you find or ask anything you can directly open issue on repository.

--

--

Mehmet Ozkaya
AWS Lambda & Serverless — Developer Guide with Hands-on Labs

Software Architect | Udemy Instructor | AWS Community Builder | Cloud-Native and Serverless Event-driven Microservices https://github.com/mehmetozkaya