DEV Community

KainatSana
KainatSana

Posted on

More than "Hello World in Lambda"πŸ€”

AWS Lambda is a serverless computing service that allows developers to run code without managing servers or infrastructure. Lambda functions can be triggered by various events and are a great way to build scalable and cost-effective applications. In this blog, we'll explore how to go beyond the "Hello, World!" example and create more complex Lambda functions.

Let's create a Lambda function that fetches data from an external API and stores it in an S3 bucket.

Step 1: Set up the AWS Environment

Before we start, make sure you have an AWS account and have set up the necessary permissions. You'll need to create an S3 bucket and an IAM role with permissions to access the bucket and execute Lambda functions.

Step 2: Create the Lambda Function

  1. Go to the AWS Management Console and navigate to the Lambda service.
  2. Click "Create function" and select "Author from scratch".
  3. Give your function a name, select your preferred runtime, and choose the IAM role you created in step.
  4. In the function code editor, copy and paste the following code:
import boto3
import requests
import json

def lambda_handler(event, context):

    url = "https://jsonplaceholder.typicode.com/posts"
    response = requests.get(url)
    data = response.json()

    s3 = boto3.resource('s3')
    bucket_name = 'your-bucket-name'
    object_key = 'data.json'
    s3.Object(bucket_name, object_key).put(Body=json.dumps(data))

    return {
        'statusCode': 200,
        'body': json.dumps('Data fetched and stored in S3!')
    }

Enter fullscreen mode Exit fullscreen mode

This code fetches data from the JSON Placeholder API and stores it in an S3 bucket. Make sure to replace "your-bucket-name" with the name of the S3 bucket you created in step 1.

Click "Deploy" to create your Lambda function.

Step 3: Test the Lambda Function

  1. Click the "Test" button and create a new test event.
  2. Give your test event a name and leave the default event template.
  3. Click "Create".
  4. Click the "Test" button again to run the test event.
  5. After the function executes, check your S3 bucket to make sure the data was stored successfully.

And that's it! You've created a Lambda function that fetches data from an external API and stores it in an S3 bucket. You can now use this function as part of a larger application or build on it to create more complex functionality.

Top comments (0)