Debug School

rakesh kumar
rakesh kumar

Posted on

Explain Amazon API Gateway in aws

Amazon API Gateway Architecture in Aws
Performing CRUD operations using AWS Lambda as a backend and integrating it with Django

Amazon API Gateway Architecture in Aws

AWS Lambda function can be invoked on HTTPS url. It can be done on GET, POST, PUT. When the HTTPS url is invoked, the AWS Lambda function can also triggered and the data passed to HTTPS using get/post can be made available inside AWS Lambda to be used to insert in DynamoDB or to send mail etc.

This chapter discusses in detail about various processes involved in work in with AWS lambda and API Gateway.

Processes involved
The following are the processes involved in working with AWS lambda and API Gateway −

  1. Create IAM role for permission
  2. Create AWS lambda function
  3. Create API Gateway
  4. Link lambda function to api gateway
  5. Passing data to api gateway A basic diagram that explains the working of API gateway and AWS Lambda is given here −

Image description

Image description

Image description
These processes are explained in detail further in this chapter with relevant screenshots.

Create IAM role for permission
From Amazon services as shown below, select IAM for creating roles to be used by Lambda function.

Image description

Go to IAM and select Roles from left side section as shown below −

Image description

Click Create role for Lambda function.

Image description

Select Lambda and click Permissions at the bottom. Select the permission required for the API Gateway and Lambda.

Image description

Search for API gateway in the search and it will list you all the related permissions. Here we have chosen full access to API gateway as shown below −

Image description

Now, search for API gateway and it will list you all the related permissions. Here we have chosen full access to API gateway as shown below −

Image description

You have to repeat the same process for Policies also.

Image description

Once you are done choosing the necessary policies, click Review for the next step. Enter the name of the role as per your choice as shown below −

Image description

It displays the policies attached to the role. Click Create role and we are done with the role creation and can proceed with the lambda function.

Create AWS Lambda Function
Go to AWS services and click on lambda service to create a function for connecting it with api gateway.

Image description

The UI screen for Lambda function is shown below. Click Create function button to proceed with creation of Lambda function.

Image description

Image description

Image description

or in python

def lambda_handler(event, context):
    return {
        'statusCode': 200,
        'body': 'Hello from AWS Lambda and API Gateway!'
    }
Enter fullscreen mode Exit fullscreen mode

AWS Lambda code is present in index.js file. The function called handler has the params namely events, context and callback.

Callback function basically has the error and the success message. Note that here we do not have any error related code, so null is passed and the success message is HelloWorld from lambda.

Lastly, save the changes added and let us proceed to add the Lambda function to the API gateway.

Create API Gateway

Login to your AWS account and open API Gateway as shown below −

Image description

Image description

Image description

Image description

Image description

Image description

Enter the Resource Name as shown below. You will see the name of the resource entered in the url created at the end. Click Create Resource and you will see it on the screen as follows −

Image description

Image description

Add GET/POST methods to the resource created as shown below. Select the method from Actions dropdown.

Image description

Click the GET method to add the method to the API.

Image description

Next step is the integration which will integrate it with Lambda function. Now add the Lambda function to it as shown below −

Image description

Link Lambda Function to API Gateway
Select the lambda function created earlier.

Image description

Save the changes and you can see a dialog box asking for permission as shown below −

Image description

Image description

Now, let us deploy the API gateway changes. For this purpose, we need to select the Deploy API from Actions dropdown as shown below

Image description

Select Deploy API. It will ask for the deployment state. Select New Stage from Deployment stage dropdown and add the stage name as Production.

Image description

Click Deploy button and it will redirect you to the url as shown below −

Image description

This is a basic example of working with AWS Lambda and AWS API Gateway. In the above example, we have hardcoded the message in Lambda function.

Now, let us take the message details from the API Gateway. Incase if the HTTPS call has to be called from a different domain, for example AJAX call to the API, we need to enable CORS for the API gateway created.

Select the reSource created for the API and click Actions dropdown −

Image description

Now, Enable CORS will open up the following screen −

Image description

You can use few methods to ENABLE CORS. Access-Control-Allow-Origin is marked as * which means it will allow to get contents from API gateway from any domain.

You can also specify the domain name you want to work with the API. Click Enable CORS and replace existing CORS headers button and it will display confirmation message as shown below −

Image description

Image description

Summary

let's create a simple AWS Lambda function in Python and expose it through Amazon API Gateway using the AWS Management Console. Here's a step-by-step guide:

Step 1: Create a Lambda Function
Open the AWS Management Console.

Navigate to AWS Lambda.

Click on the "Create function" button.

Choose "Author from scratch":

Function name: Enter a name for your Lambda function, e.g., "MyPythonLambdaFunction."
Runtime: Choose "Python 3.8."
Click on the "Create function" button.

Step 2: Add Code to Lambda Function
In the "Function code" section, replace the existing code with the following Python code:


def lambda_handler(event, context):
    return {
        'statusCode': 200,
        'body': 'Hello from AWS Lambda and API Gateway!'
    }
Enter fullscreen mode Exit fullscreen mode

Click on the "Deploy" button to save your function.

Step 3: Create an API Gateway
In the AWS Management Console, navigate to Amazon API Gateway.

Click on the "Create API" button.

Choose "HTTP API" and click on the "Build" button.

Enter an API name, e.g., "MyPythonApi."

Click on the "Add Integration" button.

Choose "Lambda Function" as the integration type.

Select the Lambda function you created earlier (e.g., "MyPythonLambdaFunction").

Click on the "Create" button.

Step 4: Deploy the API
In the API Gateway console, select your API (e.g., "MyPythonApi").

In the left navigation pane, click on "Stages."

Click on the "Create" button to create a new stage (e.g., "prod").

Click on the "Deploy" button.

Step 5: Access the API
In the API Gateway console, select your API.

In the "Stages" section, click on the URL for the deployed stage (e.g., "prod").

Accessing the URL should return the response from your Lambda function.

Congratulations! You've created a simple AWS Lambda function in Python and exposed it through Amazon API Gateway. This example demonstrates the basics, and you can customize it based on your specific use case.

Performing CRUD operations using AWS Lambda as a backend and integrating it with Django

Performing CRUD operations using AWS Lambda as a backend and integrating it with Django involves several steps. Below is a simplified example demonstrating the process. In this example, we'll use a Lambda function to handle user CRUD operations, and Django will serve as the frontend that communicates with the Lambda function through API Gateway.

Step 1: Set Up Django Project
Create a new Django project and app:

django-admin startproject myproject
cd myproject
python manage.py startapp myapp
Enter fullscreen mode Exit fullscreen mode

Define a Django model for the user in models.py:

# myapp/models.py
from django.db import models

class User(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField(unique=True)
Enter fullscreen mode Exit fullscreen mode

Run migrations:

python manage.py makemigrations
python manage.py migrate
Enter fullscreen mode Exit fullscreen mode

Create a Django template

create a Django template to take user input and make requests to your AWS Lambda function through API Gateway.

<!-- myapp/templates/user_crud.html -->
<!DOCTYPE html>
<html>
<head>
    <title>User CRUD</title>
</head>
<body>
    <h1>User CRUD Operations</h1>

    <!-- Create User Form -->
    <form method="post" action="{% url 'create_user' %}">
        {% csrf_token %}
        <label for="name">Name:</label>
        <input type="text" name="name" required><br>
        <label for="email">Email:</label>
        <input type="email" name="email" required><br>
        <button type="submit">Create User</button>
    </form>

    <hr>

    <!-- Retrieve Users -->
    <h2>Users</h2>
    <ul>
        {% for user in users %}
            <li>{{ user.name }} - {{ user.email }}</li>
        {% endfor %}
    </ul>

    <!-- Update User Form -->
    <h2>Update User</h2>
    <form method="post" action="{% url 'update_user' user.id %}">
        {% csrf_token %}
        <label for="name">New Name:</label>
        <input type="text" name="name" required><br>
        <label for="email">New Email:</label>
        <input type="email" name="email" required><br>
        <button type="submit">Update User</button>
    </form>

    <!-- Delete User Form -->
    <h2>Delete User</h2>
    <form method="post" action="{% url 'delete_user' user.id %}">
        {% csrf_token %}
        <button type="submit">Delete User</button>
    </form>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

In this template:

  1. The "Create User" form allows users to input a name and email for creating a new user.
  2. The "Retrieve Users" section displays a list of users.
  3. The "Update User" form allows users to input a new name and email for updating an existing user.
  4. The "Delete User" form allows users to delete an existing user

Step 2: Create Lambda Function
Create a new directory for your Lambda function:

mkdir lambda_function
cd lambda_function
Enter fullscreen mode Exit fullscreen mode

Create a Lambda function handler in lambda_function.py:

# lambda_function/lambda_function.py
import json
import boto3
from botocore.exceptions import ClientError

dynamodb = boto3.resource('dynamodb')
table_name = 'YourDynamoDBTableName'
table = dynamodb.Table(table_name)

def create_user(data):
    try:
        response = table.put_item(Item=data)
        return {'message': 'User created successfully'}
    except ClientError as e:
        return {'error': str(e)}

def get_users():
    try:
        response = table.scan()
        return response['Items']
    except ClientError as e:
        return {'error': str(e)}

def update_user(user_id, data):
    try:
        response = table.update_item(
            Key={'userId': user_id},
            UpdateExpression='SET #name = :name, #email = :email',
            ExpressionAttributeNames={'#name': 'name', '#email': 'email'},
            ExpressionAttributeValues={':name': data['name'], ':email': data['email']},
            ReturnValues='UPDATED_NEW'
        )
        return {'message': 'User updated successfully'}
    except ClientError as e:
        return {'error': str(e)}

def delete_user(user_id):
    try:
        response = table.delete_item(Key={'userId': user_id})
        return {'message': 'User deleted successfully'}
    except ClientError as e:
        return {'error': str(e)}

def lambda_handler(event, context):
    # Parse request body
    body = json.loads(event['body'])

    # Perform CRUD operations based on the request
    if event['httpMethod'] == 'POST':
        # Create user
        return create_user(body)
    elif event['httpMethod'] == 'GET':
        # Retrieve users
        return get_users()
    elif event['httpMethod'] == 'PUT':
        # Update user
        user_id = event['pathParameters']['id']
        return update_user(user_id, body)
    elif event['httpMethod'] == 'DELETE':
        # Delete user
        user_id = event['pathParameters']['id']
        return delete_user(user_id)
Enter fullscreen mode Exit fullscreen mode

Step 3: Set Up API Gateway
In the AWS Management Console, navigate to Amazon API Gateway.

Create a new HTTP API.

Add a new resource and method (POST, GET, PUT, DELETE) in the API.

Set up an integration for each method, linking them to your Lambda function.

Deploy the API.

Note the API Gateway endpoint URL.

Step 4: Django Integration
Install the requests library in your Django project:

pip install requests
Enter fullscreen mode Exit fullscreen mode

Create a view in your Django app that communicates with the Lambda function:

# myapp/views.py
from django.shortcuts import render
import requests
from django.http import JsonResponse

def user_crud(request):
    # API Gateway endpoint URL
    api_url = 'https://your-api-gateway-url.amazonaws.com/user-crud'

    # Example: Perform a GET request to retrieve users
    response = requests.get(api_url)

    # Process the response and return a JsonResponse
    return JsonResponse({'message': response.json()})
Enter fullscreen mode Exit fullscreen mode

Create a URL pattern in your Django app:

# myapp/urls.py
from django.urls import path
from .views import user_crud

urlpatterns = [
    path('user-crud/', user_crud, name='user_crud'),
]
Enter fullscreen mode Exit fullscreen mode

Include the app's URLs in your project's urls.py:

# myproject/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('myapp.urls')),
]
Enter fullscreen mode Exit fullscreen mode

Step 5: Test
Run your Django development server:

python manage.py runserver
Enter fullscreen mode Exit fullscreen mode

Visit http://127.0.0.1:8000/api/user-crud/ to test the Django integration with your Lambda function through API Gateway.

Remember to replace placeholder URLs with your actual AWS API Gateway endpoint and Lambda function logic. This example provides a basic structure, and you can expand it based on your specific CRUD requirements.

aws_lambda_working_wit

Top comments (0)