Thursday, June 26, 2025

lambda part2

 lambda part2

Class 53rd Lambda Part2 June 26th

Event Driven architecture :we can other resource service called lambda function(event right/s3,cloudwatch..)

Lambda function >Trigger >APIGateway we can call three option

 Websocket API:chat boat related 

HTTP API: late weight fast response, not comfort when plan give input and call lambda

REST API: it is better give input and called 

Practical:

Using Rest API, we can call lambda

Step1:Click Build,given any name ccitrestapi and then click create API

Single API we can create multiple resources click create resource, enable the  CORS

Under these resource ,we are using different, different methods,select the option and delete 

Step2: Click create method, we can able write the code in lambda function database statements also we can write and communication using below methods

API's  developer mainly these methods using CRUD(Create/read/update/delete)

C POST Create insert

R GET read

U PUT update

D DELETE  delete

The best practice use the method 

Step3: Click create method ,select you lambda function


Step4:After completion need to deploy
Step5:given the any name stage of the deployment dev 

Step6: we got one endpoint

Step7:using endpoint 
Step8: Need maintain version, when plan to change the lambda code 

Step10: click public new version given any name "first version"

Version created, here version sequence number generated 1 version,it will increase each deploy version
Step11: once you changes done the version1 backup was locked ,current version you able edit
Step12: Current version ,added text New version 1,deploy
Step13:changes are refected end point 
Step14: after every change you need publish the version then after change the code,so that maintained the version backup ,See one more version created 

you see arn also will change backups version1 and version2
Current version :arn:aws:lambda:eu-west-2:216989104632:function:ccit-lambda-function
version1 :arn:aws:lambda:eu-west-2:216989104632:function:ccit-lambda-function:1
version2: arn:aws:lambda:eu-west-2:216989104632:function:ccit-lambda-function:2

Step15: if you want to restore old version1 APIGateway>Integration request

Step16:Give you arn old existing version arn and then click save
Step17: Click Deploy API

Step18 See changes are reverted 

here we have simple code ,deployed whenever required , in production it is difficult to deployment due to required downtime ,Aliases We have create aliases complete lambda function .

Step1: Create Aliases given any name lambda-alias, Below version you can select $LATEST
Step2:we will get aliases also one arn 


Step3: This one time activity ,go API Gateway edit ,integration request >edit ,click save 
instead of version arn ,we will aliases arn 

Step4: And then click deploy API, it just create the alias for the current change. 
Step5:edit the aliases, we have change this time version 1 click save 
Step6:This time not required deploy API, base aliases it will automatically deploy and change will reflect in the end point 

Input parameter for lambda function
We able to send input parameter also to lambda function 

Step1: Create new lambda function 
We have plan to pass input endpoint ,it will reflect in output lambda endpoint ,click deploy
Step2: Need to create one REST API 

 the API Gateway select GET integration edit ,for input accept you need mapping 
Step3:mapping for inputs using below code click save 
Step5: Below code for lambdafunction and 
import json

def lambda_handler(event, context):
    body = event if isinstance(event, dict) else {}
    val = body.get('name')
    message  = f"Hello from CCIT {val.capitalize()}!"

    # TODO implement
    return {
        'statusCode': 200,     
        'body': json.dumps(message),
        'header' : {
            'Content-Type': 'application/json'
        }
    }
intergration mapping configuration code 

{
"name" : "$input.params('name')"
}

Step6: we can called query string parameter 


Practical Project
We have one application ,Our database connection and insert and update operation need perform in lambda function This is existing application connect local msqlconnector ,using instead of the using lambda for db connection
https://github.com/Vakatisubbu/DigitalLibrary


Step1: Lambda create function Signup select role and create function

One Same app.py local or any other new directory lambda_function.py create  file and execute below connect 
lambda_function.py 
import json
import pymysql

db_config = {  
    'host': 'localhost',
    'user': 'root',
    'password': 'root@123',
    'database': 'digital_library'
}

def lambda_handler(event, context):
    try:
        # 🔍 Debug full event structure
        print("FULL EVENT:", json.dumps(event))

        # ✅ Pull query parameters
        body = event if isinstance(event, dict) else {}
        print("Query Params:", json.dumps(body))

        # Extract
        name = body.get('name')
        mobile = body.get('mobile')
        email = body.get('email')
        password = body.get('password')
        gender = body.get('gender')
        location = body.get('location')
        image = body.get('image')

        if not all([name, mobile, email, password,gender,location,image]):
            return {
                "statusCode": 400,
                "body": json.dumps({
                    "status": "fail",
                    "message": "Missing required fields",
                    "received": body  # <-- debug: show what was received
                })
            }

        conn = pymysql.connect(**db_config)
        cursor = conn.cursor()

        cursor.execute("SELECT * FROM users WHERE email = %s", (email,))
        if cursor.fetchone():
            cursor.close()
            conn.close()
            return {
                "statusCode": 409,
                "body": json.dumps({"status": "fail", "message": "Email already exists"})
            }

        cursor.execute("""
            INSERT INTO users (name, mobile, email, password, gender, location, image)
            VALUES (%s, %s, %s, %s, %s, %s, %s)
        """, (name, mobile, email, password, gender, location, image))
        conn.commit()
        cursor.close()
        conn.close()

        return {
            "statusCode": 200,
            "body": json.dumps({"status": "success", "message": "User created successfully"})
        }

    except Exception as e:
        print("Exception:", str(e))
        return {
            "statusCode": 409,
            "body": json.dumps({"status": "error", "message": str(e)})
        }

C:\Git_repos\DigitalLibrary>pip install pymysql -t .
Collecting pymysql
  Using cached PyMySQL-1.1.1-py3-none-any.whl.metadata (4.4 kB)
Using cached PyMySQL-1.1.1-py3-none-any.whl (44 kB)
Installing collected packages: pymysql
Successfully installed pymysql-1.1.1
After msql package installation ,better to put separate folder lambda python file and run, nope if same also,put these three file select zip it. 



After zip PyMySQL-1.1.1.dist-info.zip

Step2: Upload for lambda function , the file should be up 10 MB ,we can use this method, more than that we need to use S3 bucket.click save 

Step3:files uploaded, click deploy
Step4:Create new API using reset api give any name
digitallib and create different and different methods click resources

First method Signup
After created ,delete the option one which came default ,Create method, choose Get
Select the Arn( here we using get for signup also for insert bue to more using Get only, but real time it should be same Post method you need use instead of Get) and click create the mehod

Step4:After the we need to edit the integration request, add the inputs in mapping template
and then click save  and click deploy API

{
   "name": "$input.params('name')",
   "mobile": "$input.params('mobile')",
   "email": "$input.params('email')",
   "password":"$input.params('password')",
   "gender": "$input.params('gender')",
   "location":"$input.params('location')",
   "image": "$input.params('image')"
}
Step6:
Step7:endpoint created successfully for signup page,you need attached query string input values

We have to add query string here ,need to pass inputs 
https://g2bi41t66a.execute-api.eu-west-2.amazonaws.com/LambdaAPI/Signup?name=Prabhu&mobile=978882322&email=prabhu@gmail.com&password=prabhu&gender=M&location=Hyderabad&image=prabhu.png

Getting error unfortunately localhost aws unable table you need created on RDS msql

Step8:Created one RDS public access yes "ccitconnectmsql"
got the end point rdsmysql.c5iyik8mi7ym.eu-west-2.rds.amazonaws.com
admin,credential , pass lambdafunction code and also create schema and tables 


Step9:if you facing any if msql security group inbound rule delete the entry give all trafic and save and try to connect
 

Step10:Please change connect details of the endpoint mysql,click deploy and try the query string parameter
Step11:Successfuly save user


Step12:Check the database level

Step13:below signin lambda code, zip this code upload inn signin

C:\Git_repos\DigitalLibrary\lambda_function>pip install pymysql -t .
Collecting pymysql
  Using cached PyMySQL-1.1.1-py3-none-any.whl.metadata (4.4 kB)
Using cached PyMySQL-1.1.1-py3-none-any.whl (44 kB)
Installing collected packages: pymysql
Successfully installed pymysql-1.1.1

one more Singin

# Replace these with your actual RDS MySQL configuration
db_config = {
    'host': 'rdsmysql.c5iyik8mi7ym.eu-west-2.rds.amazonaws.com',
    'user': 'admin',
    'password': 'admin12345',
    'database': 'digital_library'
}

def lambda_handler(event, context):
    try:
        # Support both API Gateway formats: query params or body
        if event.get('queryStringParameters'):
            data = event['queryStringParameters']
        else:
            body = event.get('body', '{}')
            data = json.loads(body) if isinstance(body, str) else body

        email = data.get('email')
        password = data.get('password')

        # Validate input
        if not email or not password:
            return {
                "statusCode": 400,
                "body": json.dumps({"status": "fail", "message": "Email and password required"})
            }

        # Connect to RDS MySQL
        conn = pymysql.connect(**db_config)
        cursor = conn.cursor()

        # Check credentials
        cursor.execute("SELECT id, name, email FROM users WHERE email = %s AND password = %s", (email, password))
        user = cursor.fetchone()

        cursor.close()
        conn.close()

        if user:
            return {
                "statusCode": 200,
                "body": json.dumps({
                    "status": "success",
                    "message": "Login successful",
                    "user": {
                        "id": user[0],
                        "name": user[1],
                        "email": user[2]
                    }
                })
            }
        else:
            return {
                "statusCode": 401,
                "body": json.dumps({"status": "fail", "message": "Invalid email or password"})
            }

    except Exception as e:
        print("Exception:", str(e))
        return {
            "statusCode": 500,
            "body": json.dumps({"status": "error", "message": str(e)})
        }

Step14:Signin above give deploy,Api gate add you method and resorce
Step15:delete OPTIONS which is coming default. create method GET 
Step16:

Step17: Go to integration request edit mapping template
{
  "email": "$input.params('email')",
  "password": "$input.params('password')"
}

Step18:Save integration 

Step19:take the endpoint query string 
https://g2bi41t66a.execute-api.eu-west-2.amazonaws.com/LambdaAPI/Signin?email=prabhu@gmail.com&password=prabhu





--Thanks