In this lab, we will create a Lambda function and web API that will retrieve a random image from a site and display it. We will use the web console to build and deploy the code.

To begin with, visit AWS Educate and go to your AWS Starter Account. Then, bring up the AWS console.

In order to practice the principle of least privileges, we will create a custom IAM role, then attach it to our function. Go to IAM=>Roles, then click "Create role"

AWS supports service-linked roles that are pre-defined, managed roles that encompass common permissions that are required for using a service. In this case, we are creating a role for Lambda so select Lambda for the type of role, then click "Next: Permissions"

Search for "Lambda" in "Filter policies", then select AWSLambdaFullAccess.

Click on "Next: Tags", then on "Next: Review", keeping the defaults. Name your role lambda-<OdinID>. Then, click "Create role"

Go back to the AWS console, then click on Lambda. Click "Create a function"

Then, select "Author from Scratch". In the configuration,

Click Add Trigger. View the various triggers within AWS that can cause the Lambda to execute including S3 storage events, SNS messages, CloudWatch events, CodeCommit events, etc.). Since we will be triggering our Lambda function via web requests, select API Gateway, the service that accommodates this.

Register the function to be executed upon a request to an API endpoint by selecting "Create an API" and specifying the HTTP API type and "Open" for security. This makes our endpoint public for all to access (compared to internal APIs that only handle requests from within a project). Then click "Add".

Click on the Lambda function to configure the function's code.

Scroll down to the code window to see the default code.

Replace the code with code that is functionally equivalent to what is shown in the image below. The function (lambda_handler) first generates a random URL to an image site with a message of the day. It then retrieves the contents of the URL and returns a dictionary object whose attributes set the HTTP response status, the Content-Type: response header, and the payload returned. This dictionary object is a special object required by API Gateway in its Integration Response in order for API Gateway to form the response that is eventually sent back to the client.

After implementing the Lambda, at the top of the interface, click "Deploy", then click "Test".

Configure and create a test event. Its body does not matter since it is ignored by our Lambda.

Click on "Test" and debug the results, if necessary. Successful execution should yield something similar to below:

Note the name of your function and go back to "API Gateway" in the console and find the endpoint for the function.

Copy the url of the default stage into your browser's URL bar, and append your lamda function's name to the end of the base url.


Visit Lambda in the AWS console. Select the Lambda created for this lab and delete it.