Serverless API on AWS in 10 minutes

Amazon Web Services (AWS) allows you to quickly prototyping simple web applications. For example, to write a set of APIs for a simple mobile application can be done in minutes.

In this article we will use DynamoDB and Gateway API (without Lambda functions) to configure GET and POST database queries with the ability to read, write and modify data in it.

First of all, you need to register on AWS and enter the console.

We will start creating the service from the DynamoDB database, click the Create table button, enter the name of the apiData table (in the manual I will use my names, you can specify any others), the main key for which will be added records: userID and pick Use default settings.

create-dynamo-db-table

In DynamoDB, rows in the table are added by specified key, it is possible to add any number of parameters and not necessarily to keep the same data structure for different keys. In our case, for each user with the specified userID, we can add any data that describes specific user.

Then, we will create a role in the Identity and Access Management service. In the left menu, select the Roles section and click the Create new role button and specify its name – dynamoAPI, and after clicking Next Step – in the AWS Service Roles section select Amazon API Gateway, click Next Step and finally Create Role.

We are interested in the value of Role ARN specified in the format arn:aws:iam::000000000000:role/roleName. This value will need to be used when querying the database, so write it down. Next, we need to create an access policy for this role, this can be done on the Permissions tab in the Inline policies section, expand it and click on click here.

permissions-role-ARN

In the Policy Generator section, click the Select button, on the appeared page, select the Amazon DynamoDB service and specify the following Actions:

  • DeleteItem
  • GetItem
  • PutItem
  • Query
  • Scan
  • UpdateItem

If you’ll need to do some other actions with your API, in that case – you can study them on AWS API Reference page, for basic operations we have enough of these actions for now. As for Amazon Resource Name – here you can either specify the ARN of your table (located on the Overview tab), or specify * that will allow users with the to have access to all tables of your account. Click the Add Statement and then Next Step button. On the opened page – Apply Policy. This completes the configuration of the role!

Let’s move on to creating an API using the Gateway API service. Click the Create API button, on the page that appears, specify its name – The API and click the Create API button at the bottom of the page. Now we need to create a resource that can be accessed with requests, click the Actions button and select Create Resource.

aws-api-create-resource

Lets name this resource user, it will contain information about users, and to access a specific user – you will need to specify the user ID as the path parameter. In order to create such parameters in the Gateway API service, we need to create a new resource to the level below the already created user, and specify the {userid} and as the Resource Name and Resource Path you should state {userid} (note that when you specify a name in this format, the Resource Path will be automatically replaced by -userid-, you need to manually specify the desired form for the path parameter).

aws-api-new-child-resource

Next, create a method for creating a record for a new user, for this select the resource {userid}, and clicking the Actions button select Create method, specify its type – POST and click the check box to create it. In the settings menu, in the Integration type section, open the advanced show spoiler and select AWS Service Proxy.

Settings:

  • AWS Region: specify the region where your database is located (by default – us-east-1, you can check it in the Overview section of your table)
  • AWS Service: DynamoDB
  • AWS Subdomain: leave blank
  • HTTP method: POST (used for any calls to DynamoDB, including data retrieval)
  • Action Type: Use action name
  • Action: PutItem (used to create a new record / overwrite the entire value at the specified key)
  • Execution role: specify the role that we created in the format arn:aws:iam::000000000000:role/roleName

aws-service-proxy-settings

After saving these settings, you must first set Method Request, in the API Key Required select true and click on the checkbox to save the settings – this is necessary to access this method from the outside with the authorization token (do not forget to do this for all methods!). Go back and go to the second Integration Request box to set up the query in DynamoDB. Scroll down to the bottom and open the Body Mapping Templates section, click the Add mapping template button, specify the Content type: application/json, specify the query parameters in the input field, use the following code to create a new code:

{ 
    "TableName": "apiData",
    "Item": {
        "userID": {
            "S": "$input.params('userid')"
            },
        "parameter": {
            "S": "$input.path('$.parameter')"
            }
    },
    "ReturnValues": "ALL_OLD"
}

Here we specify the name of the table in which the changes are made, the first key to be entered is the userID, its value is taken from the parameter of the userid path. From the body of the request, the data on the parameter key is taken and added to the column of our database with the same name for the specified user. As a response, the previous value is sent to the specified key, if it existed. If a user with that username does not exist, an empty response will arrive.

Now we need to check if the request will work fine, for this at the top of the page, click the back button and to the right of the four squares – click on the Test button:

serverless-aws-api-execute-method

In the opened window, we need to specify the value of the Path parameter – this is the name of the user we want to create/recreate (remember, PutItem overwrites the entire string with the specified key), now specifying the request itself:

{
  "parameter": "112233"
}

If the request was successful then we’ll receive a response with an empty body:

serverless-aws-api-execute-method-response

If we we’ll look to DynamoDB, then on the Items tab we can see the newly created user:

aws-dynamodb-apidata

In order to read user data, you need to create a GET method with Action – Query within the {userid} resource, perform configuration of the integration request (remember – in this case, the database query is still POST method!) and specify the following template for the body mapping:

{
    "TableName": "apiData",
    "KeyConditionExpression": "userID = :v1",
    "ExpressionAttributeValues": {
        ":v1": {
            "S": "$input.params('userid')"
        }
    }
}

If you want to change some parameter values for a certain user without changing all other lines, then we can use the POST method with Action of the UpdateItem type:

{
    "TableName": "apiData",
    "Key": { 
    "userID": {
            "S": "$input.params('userid')"
        }
    },
    "UpdateExpression": "set token_proof = :tkn",
    "ExpressionAttributeValues": { 
    ":tkn": {
            "S": "$input.path('$.token')"
        }
    },
    "ReturnValues": "UPDATED_NEW"
}

Incase of success, the request returns all updated user data, this method can be used to store appsecret_proof when authorizing the user through Facebook in your application.

Actually, all the basic scenarios for using the API can be created based on these examples. All that remains for us is to access the API from the outside, for this you need to click our beloved Actions button in the menu of our API and select the Deploy API.

Specify:

  • Deployment stage: [New Stage]
  • Stage name: apiRelease (or any other)

Click Deploy and get the Invoke URL like this: m00000000a.execute-api.us-east-1.amazonaws.com/apiRelease. To make requests on this address – you need an authorization token, to get it – in the left menu go to the API Keys section, click the Create button, name your key and save it. Next, in the appeared API Stage Association section select the desired API and the newly created scene, then click the Add button. Go back through the left menu to our API, select Actions -> Deploy API, select an already created Stage and click Deploy.

This is it!

Now you can make requests to your API from the outside by adding x-api-key header to your requests with your token as a value. To get data about our created user, just make the corresponding GET request to the address m00000000a.execute-api.us-east-1.amazonaws.com/apiRelease/user/newUserOne and you will get all the information about it in the response! Thus, in a matter of minutes you can create a simple API to access the database, through which you can test your new application or any other service that does not require a complex data structure.

LEAVE A REPLY

Please enter your comment!
Please enter your name here