API Gateway to Lambda Functions

Jul 5, 2024

API Gateway to Lambda Functions

Introduction

  • Create a RESTful API Gateway endpoint to invoke a Lambda function.
  • Return JSON to the client.

Steps

Create Lambda Function

  1. Function Name: TransactionHandler.
  2. Input: Event object with query string parameters.
  3. Resource Setup: Transactions resource with a GET API forwarding requests to the Lambda function.
  4. Response: Hard-coded response (in applications, process query parameters and interact with other AWS services).
  5. Testing: Invoke endpoint from the browser and observe response.

Console Actions

Lambda Setup

  1. Navigate to Lambda Section.
  2. Create Function: From scratch, named TransactionProcessor.
  3. Runtime: Python 3.6.
  4. Permissions: Basic CloudWatch permissions (included in new role with basic Lambda permissions).
  5. Click Create.

Coding in Sublime Text

  1. Steps in Function
    • Parse query string parameters (transactionID, transactionType, amount).
    • Print parameters for verification.
    • Construct response body as a JSON object.
    • Include echo values received and a custom message.
    • Build HTTP response object with status code, headers, and body.
    • Return the response.
  2. Code Move: Copy from Sublime Text to Lambda console and save.

API Gateway Setup

  1. Navigate to API Gateway Section.
  2. Create API: Select New API.
    • Name: TransactionAPIs.
    • Endpoint Type: Default.
  3. Create Resource: Named transactions.
  4. Create Method: GET method.
    • Backend: Lambda function.
    • Lambda Proxy Integration: True.
    • Lambda Function: TransactionProcessor.
    • Save and grant API Gateway permission to invoke Lambda.

Deploy API

  1. Navigate to Deploy API.
  2. Create Stage: Name it test.
  3. Deploy: Test environment deployed.
    • Endpoint URL: Copy the URL.
  4. Send Request from browser with query string parameters.

Testing and Verification

  • Example Call: /transactions?transactionID=5&type=purchase&amount=500.
    • Expected JSON Response: { transactionID: 5, type: 'purchase', amount: 500, message: 'Hello from LambdaLand' }.

CloudWatch Logs

  • Navigate to CloudWatch.
  • Logs: Verify logs for transaction ID, type, and amount.

Conclusion

  • Quick wrap-up of creating and testing API Gateway with Lambda integration.
  • Encourage viewers to share use cases.
  • Reminder to like and subscribe.