Configuring HTTPS Endpoints on AWS Lambda Functions with AWS Lambda Function URLs
By: Date: 20/04/2022 Categories: AWS,AWScommunity Tags:

Introduction

There are a few things to consider when deciding when to use a function URL versus building an API Gateway endpoint. Function URLs are best suited for single-function microservices with a public endpoint that doesn’t require the advanced functionality of API Gateway. Function URLs can be used to apply the following patterns:

  • Mono-Lambda APIs: Routing all requests to a single Lambda function, which in turn handles the routing to your business logic
  • Service-to-Service communication: Applying built-in AWS IAM authentication with other services
  • Lightweight webhooks: Integrating a Lambda function with Slack or GitHub

A function URL can be configured on new and existing AWS Lambda functions. In this lab step, you will create a new Lambda function and configure it with a function URL. The function will serve images from an S3 bucket which you will test by navigating to the function URL in a browser window.

Instructions

1. In the AWS Management Console, in the search bar at the top, enter Lambda, and under Services, click the Lambda result:

alt

The Functions table will load.

2. Click Create function to begin:

alt

3. On the Create function page, ensure Author from scratch is selected, then configure the following settings:

  • Function name: Enter GetImages
  • Runtime: Select Python 3.8
  • Permissions: Expand Change default execution role
    • Execution role: Select Use an existing role
    • Existing role: Select the IAM role that matches the pattern cloudacademylabs-LambdaExecutionRole-XXXX
alt

4. Click to expand the Advanced settings section:

alt

5. Click Enable function URL :

alt

The function URL settings will appear. 

6. For the function URL Auth type, select NONE:

alt

The function URL’s authentication type can be AWS_IAM or NONE.

The AWS_IAM auth type only allows authenticated IAM users and roles to make requests to your function URL. If the URL is accessed without an authenticated IAM user or role, a 403 Forbidden error will be returned.

When the auth type of a function URL is set to NONE, the URL endpoint can be accessed by the public. The function created in this lab will not require authentication. This lab will demonstrate how to invoke the function using the function URL in a browser, where no IAM user/role credentials are accessible, which requires the auth type to be set to NONE. 

The info card that appears after you select NONE explains the resource-based policy that is attached to the function as a result:

alt

You can view this policy by expanding the View policy statement section. This policy is scoped to the GetImages function and allows public access via the function URL.

Note: This setting was selected for demonstration purposes. Be aware that a function URL that is accessible to the public means unauthenticated users can invoke your function which will incur the standard invocation costs

Notice the option to enable Cross-origin resource sharing (CORS). Similar to enabling cross-origin resource sharing on an S3 bucket or API Gateway, this feature will allow access to your function URL from any origin. This function does not require CORS to be enabled so you can leave this setting unchecked:

alt

8. Click Create function:

alt

The function will be created with a default lambda_handler that returns the message “Hello from Lambda!”

9. In the Function overview section of the GetImages details page, click the Function URL to invoke the function in a new browser tab:

alt

The function message appears in the new tab:

alt

10. Return to the GetImages detail page tab and scroll down to the Code source section. 

11. Ensure the lambda_function.py file is open in the code editor and replace its contents with the following Python code:

Copy codeimport base64
import boto3
 
s3 = boto3.client('s3')
 
def lambda_handler(event, context):
    animal = 'cat'
    if 'queryStringParameters' in event:
        animal = event['queryStringParameters']['animal']
 
    response = s3.get_object(
        Bucket='cloudacademylabs-imagebucket-1u2txzxsqze7i',
        Key= animal + '.jpeg',
    )
    image = response['Body'].read()
 
    return {
        'headers': { "Content-Type": "image/jpeg" },
        'statusCode': 200,
        'body': base64.b64encode(image),
        'isBase64Encoded': True
    }
alt

Since this function is dealing with images, the base64 module is imported along with boto3 which provides access to the AWS SDK. 

The function will access a preconfigured Amazon S3 bucket in this account that was created on your behalf. The bucket contains animal images which you will retrieve and serve using this function. 

In lambda_handler, an animal variable is set to cat as the default value. The conditional statement you see next will check for a key named queryStringParameters within the event passed into the function which represents a map of query parameter keys and values. If the query string parameter with the key name animal exists, that value will be set as the animal string variable.

Next, the S3 get_object method is called, specifying the preconfigured S3 bucket name and an object key comprised of the animal variable and the .jpeg file extension. The file is then read and stored in the image variable. 

Finally, a response is returned with a content type of image/jpeg, a status code of 200, and your Base64 encoded image retrieved from the bucket. 

12. Click Deploy above the code editor to deploy your changes:

alt

You will receive the following success message when your deployment has been completed:

alt

13. Click the Function URL in the Function overview section or navigate back to the existing browser tab and refresh the page:

The following cat image will appear:

alt

Notice the URL in the browser tab. It follows this URL pattern:

https://{url-id}.lambda-url.{region}.on.aws

As it was mentioned previously, the cat image is returned when no query string parameters are presented alongside the function URL. 

13. To retrieve another animal image, append the string /?animal=dog to the end of the URL and click enter on your keyboard:

https://{url-id}.lambda-url.{region}.on.aws/?animal=dog

alt

Your function will detect the query string parameter key of animal and use that value to generate the S3 object key. The dog.jpeg image object is then retrieved and returned to the browser.

Now update the animal query string parameter to birdand click enter to view a new animal image.

Note: The S3 bucket only contains an image for the values cat, bird, and dog. A query string parameter of anything besides those three images will return an internal server error, which indicates the lambda function failed with an “Object not found” error. 

Summary

In this lab step, you created a new AWS Lambda function and configured it with a function URL. You also invoked the Lambda function from a browser window without the need to create a separate HTTPS endpoint.

Enabling a Function URL on an Existing AWS Lambda Function

Introduction

In this lab step, you will configure a function URL on an existing Lambda function. This lab step will walk you through configuring a function URL on an existing Lambda function within the AWS console. If you’re interested in creating a function URL using the AWS CLI or AWS CloudFormation, refer to the following AWS documentation:

Instructions

1. Return to the AWS Lambda Functions page.

2. Click the cloudacademylabs-HelloWorldHTML-XXXX function name to begin:

alt

In the function details page, you will notice the following function code in the Code source editor:

alt

This simple Python function returns a Hello, World string wrapped in an h1 HTML element. The response body will be returned as a content type of text/html.

3. To attach a function URL to HelloWorldHTML, click the Configuration tab:

alt

4. Click Function URL in the left navigation pane:

alt

5. Click Create function URL:

alt

6. Similar to the first function in this lab, select NONE for the URL’s Auth type, then click Save at the bottom of the page:

alt
alt

You will be redirected back to the Function URL configuration page.

7. Click the Function URL to open it in a new browser and invoke your function:

alt
alt

The Hello, World message is displayed on the new browser page, indicating a successful invocation.

Summary

You have now successfully completed the following tasks as a part of this hands-on lab:

  • Configured a Function URL on a new and existing AWS Lambda Function