iTranslated by AI
Building a REST API with AWS: A Hands-on Guide
What is AWS?
A cloud service that allows flexible and rapid use of various IT resources such as servers, storage, and databases via the internet.
In this article, we will use the following services.
Amazon API Gateway
- Allows creating APIs through a combination of resources and methods.
- Routes HTTP requests received from clients to specific APIs.
AWS Lambda
- Provides an editor for program creation and a serverless execution environment.
- Create the actual logic of the API built with API Gateway as a Lambda function.
Amazon DynamoDB
- A fast and flexible NoSQL database.
- Used to hold data utilized by Lambda functions.
AWS IAM
- Allows setting up authentication and authorization.
- Used to grant Lambda functions the permissions needed to access DynamoDB.
Precautions when using AWS
For example, if the region where API Gateway is built differs from the region where the Lambda function is built,
issues such as the Gateway being unable to call the Lambda function may occur.
Therefore, in this tutorial, we will build all AWS services in the Tokyo region.
What is a REST API?
API stands for "Application Programming Interface."
A REST API is an API based on principles such as the following.
(By the way, REST stands for "Representational State Transfer.")
Client-Server
The client and server are independent of each other and completely separated.
Stateless
Ensure that state management, such as sessions, is not handled on the server side.
Uniform interface
Uses methods defined by the HTTP protocol.
Specifically, operations such as GET, POST, PUT, and DELETE are used.
Addressability
All resources are represented by unique URIs.
Prerequisites
- It is assumed that an AWS account has already been created.
- This REST API can be created without issue even within the AWS Free Tier.
Creating the users Table in DynamoDB
-
Access the DynamoDB page and click "Create table".

-
Set the Table name to "users" and the Partition key to "id", then create the table.

Creating an IAM Role
-
Access the IAM page, select "Roles" from the side menu, and
then click "Create role".

-
Select "AWS service" for the Trusted entity type and
"Lambda" for the use case, then click "Next".

-
For the Permission policies, select "AWSLambdaBasicExecutionRole" and
"AmazonDynamoDBFullAccess", then click "Next".


-
Set the Role name to "users_role" and click "Create role".

Creating Lambda Functions
-
Access the Lambda page and click "Create function".

-
Set the function name and set the runtime to "Python". For the execution role, select "Use an existing role", choose the "users_role" you created earlier, and click "Create function".

Functions to be Created
- POST
- GET
- PUT
- DELETE
Let's create four functions corresponding to these four types of HTTP methods.
users_post_function
import json
import boto3
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('users')
def post_users(requestJSON):
table.put_item(Item={
'id': requestJSON['id'],
'user_name': requestJSON['user_name'],
'email': requestJSON['email'],
'age': requestJSON['age'],
'phone_number': requestJSON['phone_number']
})
def lambda_handler(event, context):
requestJSON = json.loads(event['body'])
post_users(requestJSON)
users_get_function
import boto3
import json
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('users')
# If an ID is specified in the request, retrieve and return the user information for that ID
def get_user(id):
response = table.get_item(Key={'id': id})
return response['Item']
# If no ID is specified in the request, retrieve and return all user information
def get_users():
response = table.scan()
return response['Items']
def lambda_handler(event, context):
user_id = event.get("id")
if user_id:
return get_user(user_id)
else:
return get_users()
users_put_function
import json
import boto3
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('users')
def put_users(requestJSON):
table.update_item(
Key={
'id': requestJSON['id']
},
UpdateExpression='SET user_name = :newUserName, email = :newEmail, age = :newAge, phone_number = :newPhoneNumber',
ExpressionAttributeValues={
':newUserName': requestJSON['user_name'],
':newEmail': requestJSON['email'],
':newAge': requestJSON['age'],
':newPhoneNumber': requestJSON['phone_number']
}
)
def lambda_handler(event, context):
requestJSON = json.loads(event['body'])
put_users(requestJSON)
users_delete_function
import boto3
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('users')
# If an ID is specified in the request, delete the specified user
def delete_user(id):
table.delete_item(
Key={
'id': id
}
)
def lambda_handler(event, context):
user_id = event.get("id")
if not user_id:
return {
'statusCode': 400,
'body': 'id is required'
}
return delete_user(user_id)
Supplementary Information
About 【boto3】
The official SDK that allows you to operate and manage various AWS services from Python.
By the way, the formal name is "AWS SDK for Python".
In these functions, this library is used to perform DynamoDB operations.
About 【def lambda_handler】
The function that runs first when Lambda is invoked.
The argument event is the data passed at the time of invocation (such as HTTP requests or JSON).
context indicates information about the execution environment. In these functions, only event is used.
Creating an API with API Gateway
Creating users_api
-
Access the API Gateway page and click "Create REST API".

-
Set the API name to "users_api" and click "Create API".

Creating a Resource
- Set the Resource name to "users" and click "Create resource".
Creating Methods
-
With the "users" resource selected, click "Create method".
-
Select the appropriate method type.
Since we are creating four methods (POST, GET, PUT, and DELETE), you will need to perform the method creation process four times.

-
Specify the Lambda function created earlier in the Lambda function field and
click "Create method".
(Example: If the method type is POST, specify "users_post_function")

Configuring Mapping Templates
Once the methods are created, let's configure the mapping templates.
-
Selecting a method will display tabs like the following.
Here, select "Integration request" and click the "Edit" button.

-
Scroll down to find the mapping template section and edit it.
Set the Content-Type to "application/json" and
configure a different JSON for the template body based on each HTTP method.

POST, PUT
{
"body" : "$util.escapeJavaScript($input.body)"
}
GET, DELETE
{
"id" : "$input.params('id')"
}
Verifying REST API Operation
In this section, we will use the curl command to easily verify the operation. We will perform the verification in the order of POST -> GET -> PUT -> DELETE.
Working Environment
- Windows 11
- PowerShell
Creating post001.json
Create a JSON file in advance to use for verifying the POST method.
{
"id": "001",
"user_name": "中村 亮",
"email": "ryonakamura@example.com",
"age": 33,
"phone_number": "090-1111-1111"
}
Verifying the POST Method
Try running the following curl command in the directory where post001.json is stored.
By the way, you can find the [URL] part by selecting the method under the users resource in your stage.

The URL is listed in the blurred part
curl.exe -X POST -H "Content-Type: application/json" -d '@post001.json' [URL]
Verifying the GET Method
To confirm whether the data just POSTed is actually stored in DynamoDB, run the following curl command.
You can GET only the data for id:001 by adding "?id=001" to the end of the URL.
curl.exe -X GET [URL]?id=001
Creating put001.json
Create a JSON file in advance to use for verifying the PUT method.
{
"id": "001",
"user_name": "田中 健",
"email": "tanakaken@example.com",
"age": 37,
"phone_number": "090-9999-9999"
}
Verifying the PUT Method
Now, let's replace the data for id:001 using the PUT method.
If successful, run the previous GET command again to confirm that the data has been correctly replaced.
curl.exe -X PUT -H "Content-Type: application/json" -d '@put001.json' [URL]
Verifying the DELETE Method
Finally, let's delete the data for id:001 using the DELETE method.
You can DELETE only the data for id:001 by adding "?id=001" to the end of the URL.
curl.exe -X DELETE [URL]?id=001
Conclusion
The REST API introduced this time has a very wide range of applications. For example...
- SPA (Single Page Application)
- Desktop Apps
- Mobile Apps
- IoT
- Games
There are many other uses besides these.
Therefore, it can be said that REST API is an essential skill for modern engineers.
Discussion