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 −
- Create IAM role for permission
- Create AWS lambda function
- Create API Gateway
- Link lambda function to api gateway
- Passing data to api gateway A basic diagram that explains the working of API gateway and AWS Lambda is given here −
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.
Go to IAM and select Roles from left side section as shown below −
Click Create role for Lambda function.
Select Lambda and click Permissions at the bottom. Select the permission required for the API Gateway and Lambda.
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 −
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 −
You have to repeat the same process for Policies also.
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 −
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.
The UI screen for Lambda function is shown below. Click Create function button to proceed with creation of Lambda function.
or in python
def lambda_handler(event, context):
return {
'statusCode': 200,
'body': 'Hello from AWS Lambda and API Gateway!'
}
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 −
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 −
Add GET/POST methods to the resource created as shown below. Select the method from Actions dropdown.
Click the GET method to add the method to the API.
Next step is the integration which will integrate it with Lambda function. Now add the Lambda function to it as shown below −
Link Lambda Function to API Gateway
Select the lambda function created earlier.
Save the changes and you can see a dialog box asking for permission as shown below −
Now, let us deploy the API gateway changes. For this purpose, we need to select the Deploy API from Actions dropdown as shown below
Select Deploy API. It will ask for the deployment state. Select New Stage from Deployment stage dropdown and add the stage name as Production.
Click Deploy button and it will redirect you to the url as shown below −
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 −
Now, Enable CORS will open up the following screen −
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 −
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!'
}
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
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)
Run migrations:
python manage.py makemigrations
python manage.py migrate
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>
In this template:
- The "Create User" form allows users to input a name and email for creating a new user.
- The "Retrieve Users" section displays a list of users.
- The "Update User" form allows users to input a new name and email for updating an existing user.
- 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
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)
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
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()})
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'),
]
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')),
]
Step 5: Test
Run your Django development server:
python manage.py runserver
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.
Top comments (0)