AWS Lambda Code Example based on Python

CK CK 3788 
Created at  
334 0 0

AWS Lambda is a serverless compute service that lets you run code without provisioning or managing servers. You can upload your code (in various languages) and Lambda automatically executes it in response to events, like API calls, file uploads, or database updates. It scales automatically, ensuring your code runs smoothly even under heavy load, and you only pay for the compute time consumed, making it cost-effective for applications with varying usage patterns. 

 

AWS Lambda function in Python. This function is triggered by an HTTP request from Amazon API Gateway and responds with a JSON message. It demonstrates how to handle an HTTP request and return a structured JSON response.

Step 1: Define the Lambda function in Python

Create a file named lambda_function.py with the following code:

import json

def lambda_handler(event, context):
    # Extract information from the event
    name = event.get("queryStringParameters", {}).get("name", "World")
    
    # Construct the response
    response = {
        "statusCode": 200,
        "body": json.dumps({
            "message": f"Hello, {name}!"
        }),
        "headers": {
            "Content-Type": "application/json"
        }
    }
    
    return response

 

Explanation

  • event: Contains data passed by the event source, such as query parameters or HTTP request details.
  • context: Provides runtime information like AWS request ID and memory limits.

 

In this example:

  • The function checks for a "name" parameter in the query string.
  • If no "name" is specified, it defaults to "World".
  • The function then returns a JSON response with a greeting message.

 

Step 2: Deploy the Lambda Function

  1. Create a Lambda function in the AWS Lambda Console and select Python 3.x as the runtime.
  2. Copy the code into the Lambda console or upload it as a zip.
  3. Configure API Gateway to trigger the Lambda function:
    • In the API Gateway Console, create a new API.
    • Set up a new resource and method (e.g., GET) linked to your Lambda function.

 

Testing the Lambda

After deploying, you can test the endpoint by making an HTTP request. For example:

curl "https://<your-api-id>.execute-api.<region>.amazonaws.com/<stage>/hello?name=Alice"

The response should look like this:

{
  "message": "Hello, Alice!"
}

This simple example can be expanded to perform complex tasks like interacting with AWS services, processing data, and integrating with other applications.
 

Tags AWS Lambda Python Lambda Facebook X
Comments 0
Similar posts
  1. Messaging Platform with Limited TPS based on the vendor
    198
  2. Building an AWS SAM(Serverless Application Model) Project
    899
  3. AWS Lambda Example based on Teraform
    901
  4. Image Moderation Chatbot - a serverless chatbot on AWS that monitors chat channels and removes images suggestive or explicit image
    10,426
  1. Python Quizs
    502
  2. Automated OpenAPI documentation for a Python Flask API
    1,120
  3. Automated API documentation for a Django REST Framework (DRF) project using drf-yasg (Yet Another Swagger Generator)
    1,030
  4. Uploading a file to a Google Drive Folder programmatically with Python
    3,307
  5. Garbage Collection when your system does not have enough memory in your Python App
    1,014
  6. Method to maximize full CPU performance with Python
    317
  7. How do I get the maximum available of thread in python?
    991
  8. Using Queue Algorithm with Redis - RPUSH and LPOP
    770
  9. Use cache concept with Redis : Let's do Redis programming with Python
    533
  10. Installing Python 3.8 in a venv environment on CentOS 7
    463
  11. CUDA versus OpenCL
    579
  12. Simple gRPC server based on Python
    396
  13. Python code to convert PDF file to Excel Spreadsheet
    701
  14. Python script to list files on your Google Drive and download one of them
    941
  15. Coinbase Python API - Basic Example
    462
  16. Python code using GPU on CentOS with AWS
    1,252
  17. Video Scence Detection with PySceneDetect
    2,323
  18. Python Audio Separation Libraries allowing you to isolate individual tracks
    1,446
  19. Python Version Control for Library Compatibility with pyenv - Downgrading/Upgrading Python Version
    908
  20. Deleting a specific user voice from the original audio track with Python
    549
  21. Creating an MR from the original MP3 audio in Python - Deleting Voice Track from Audio File
    441
  22. Creating mp3 audio file based on the text input with Python
    466
  23. Implementing Text To Speech / Audio with Python3 and pyttsx3
    355
  24. Building Initial Virtual Environment at Python - The first step you should do for Python Programming
    559
  25. Python Simplified Assignment Operators
    533
  26. Trackback module used for Python Threading debugging
    844
  27. Python Flask with simple HTML files to server web pages along with API
    927
  28. Python Flask web server tutorial from the scratch
    623
  29. Simple Web Server based in Python
    374
  30. Thread Implementation in Python
    509
Recently updated
  1. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    42
  2. Why SPF and DKIM Are Essential for Linux Email Servers?
    36
  3. How do I create animated background for Google Meet?
    21,044
  4. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    252
  5. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    94
  6. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    157
  7. Array of arguments passed to script in PHP
    90
  8. Invalid Auction Storms in Ad Tech
    98
  9. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    202
  10. The Two Clocks of Ad Server Architecture
    71
  11. Frequency Cap Architecture Overview
    515
  12. Collecting Proof-of-Play from 100,000 Screens
    146
  13. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    288
  14. What is RedisVL?
    109
  15. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    232
  16. TPU & GPU Cluster Management Tools
    245
  17. The Concept of Scaffolding in AI Agents
    234
  18. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    583
  19. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    259
  20. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    339
  21. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    202
  22. Machine Learning: Training vs. Ranking
    222
  23. The Continuous Learning Machine: Designing a Loop That Actually Turns
    222
  24. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    195
  25. Designing a Data Curation System Around a Vector Database
    221
  26. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    257
  27. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    656
  28. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    196
  29. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    219
  30. Understanding Data Lineage
    263