Server-less API on AWS in 15 minutes
- Tutorial
Amazon Web Services allows you to quickly prototype simple web applications, and you can write an API, for example, for a simple mobile application in minutes. We will use a bunch of DynamoDB and API Gateway (without Lambda functions!) To configure GET and POST requests to the database with the ability to read, write and modify data in it.
First of all, you need to register for AWS and log in to the console. We will start creating our service with 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 by which entries will be added to it: userID and check Use default settings .
In DynamoDB, rows are added to the table by the specified key, however, it is possible to add any number of parameters and not necessarily coincide the data structure for different keys. In our case, for each of the users for the specified userID, we can add any data that describes this user.
Next, we need to create a so-called role in the Identity and Access Management service . In the menu on the left, select the Roles section and click the Create new role button; specify its name - dynamoAPI , and after clicking Next Step - in the AWS Service Roles section, select Amazon API Gateway , double-click Next Step and finally - Create Role .
We are interested in the Role ARN value specified in the format arn: aws: iam :: 000000000000: role / roleName . This value will need to be used when linking queries to the database, so write it down. Next, we need to create an access policy for this role, this is done on the Permissions tab in the Inline policies section , expand it and click click here .
In the Policy Generator sectionclick the Select button , on the page that opens, select the Amazon DynamoDB service and specify the following Actions :
You may want to be able to do some other actions using your API, in which case you can study them on this help page , for basic operations we will have enough of these actions for our eyes. As for the Amazon Resource Name item , here you can either specify the ARN of your table (located on the Overview tab ), or specify * which will allow users with the created role to have access to all the tables in your account. Click the Add Statement button and Next Step , on the page that opens - Apply Policy . This completes the role configuration!
Moving on to creating an API using the Gateway API service. Click the blue Create API button , on the page that opens, 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 .
We will call this user resource , it will contain information about users, and in order to access a specific user, you will need to specify the user ID as a path parameter. In order to create such parameters in the API Gateway service, we need to create a new resource one level below the user already created, and as the Resource Name and Resource Pathspecify {userid} (note that when specifying a name in this format, the Resource Path is automatically replaced by -userid- , you must manually specify the desired form for the path parameter).
Next, create a method to create a record for a new user, for this we select the {userid} resource , and by clicking the Actions button we select Create method , specify its type - POST and click the checkmark to create it. In the settings menu that opens, in the Integration type section, you must open the Show advanced spoiler and select AWS Service Proxy . Settings:
After saving these settings, you must first go to the first square of the Method Request , select True in the API Key Required item and click on the checkmark to save the settings - this is necessary to access this method from the outside using an authorization token (set up later; do not forget to do this operation for all methods!). Go back and go into the second Integration Request square to configure the request itself in DynamoDB. On the page that opens, scroll to the very bottom and open the Body Mapping Templates section , click the Add mapping template button , specify Content type : application / json, in the input field you must specify the request parameters, to create a new record use the following code:
Here we indicate the name of the table in which we make the changes, the key is indicated first by which the data will be entered: userID , its value is taken from the userid path parameter . Data on the parameter key is taken from the request body and added to the same column in our database for the specified user. As an answer - the previous value is sent for the specified key, if it existed. If a user with that username did not exist, an empty answer will come.
All that remains for us is to check the operation of the request, 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 with the Harry Potter icon:
In the window that opens, we will need to specify the valuePath parameter is the name of the user we want to create / recreate (I recall, PutItem overwrites the entire line with the specified key), just below - specify the request body:
The request was successful, we received a response with an empty body without any errors!
If we switch to DynamoDB , then on the Items tab we can see the user that we just created:
To read user data, you also need to create a GET method with Action - Query within the {userid} resource , configure the integration query (remember - in this case a request to the database is still done using the POST method!) and specify the following template for body mapping:
If we want to change some parameter values for a specific user without changing all the other lines, then we can also use the POST method with the Action type UpdateItem and the following mapping template:
In this case, the request returns all updated data about the user in case of success, from examples - this method can be used to store appsecret_proof when authorizing the user through Facebook in your application.
In fact, all basic API usage scenarios 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 favorite Actions button in our API menu and select Deploy API . Specify:
Press Deploy and get the Invoke URL of the following form: m00000000a.execute-api.us-east-1.amazonaws.com/apiRelease . To make requests to this address - an authorization token is required, to receive it - go to the API Keys section in the menu on the left , click the Create button , name your key somehow and save it. Next, in the API Stage Association section that appears, select the desired API and the newly created scene, then click the Add button . Return through the left menu to our API, select Actions -> Deploy API , select the already created Stage and click Deploy . Voila!
Now you can make requests to your API from the outside by adding header x-api-key with your token as a value to the request . To get data about our created user, it is enough to make a 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 him in the answer! Thus, in a matter of minutes, you can create a simple API for accessing the database, with which you can test your new application or any other service that does not require a complex data structure. For more complex projects, of course, it is worth using more suitable tools.
First of all, you need to register for AWS and log in to the console. We will start creating our service with 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 by which entries will be added to it: userID and check Use default settings .
In DynamoDB, rows are added to the table by the specified key, however, it is possible to add any number of parameters and not necessarily coincide the data structure for different keys. In our case, for each of the users for the specified userID, we can add any data that describes this user.
Next, we need to create a so-called role in the Identity and Access Management service . In the menu on the left, select the Roles section and click the Create new role button; specify its name - dynamoAPI , and after clicking Next Step - in the AWS Service Roles section, select Amazon API Gateway , double-click Next Step and finally - Create Role .
We are interested in the Role ARN value specified in the format arn: aws: iam :: 000000000000: role / roleName . This value will need to be used when linking queries to the database, so write it down. Next, we need to create an access policy for this role, this is done on the Permissions tab in the Inline policies section , expand it and click click here .
In the Policy Generator sectionclick the Select button , on the page that opens, select the Amazon DynamoDB service and specify the following Actions :
- DeleteItem
- Getitem
- Putitem
- Query
- Scan
- Updateitem
You may want to be able to do some other actions using your API, in which case you can study them on this help page , for basic operations we will have enough of these actions for our eyes. As for the Amazon Resource Name item , here you can either specify the ARN of your table (located on the Overview tab ), or specify * which will allow users with the created role to have access to all the tables in your account. Click the Add Statement button and Next Step , on the page that opens - Apply Policy . This completes the role configuration!
Moving on to creating an API using the Gateway API service. Click the blue Create API button , on the page that opens, 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 .
We will call this user resource , it will contain information about users, and in order to access a specific user, you will need to specify the user ID as a path parameter. In order to create such parameters in the API Gateway service, we need to create a new resource one level below the user already created, and as the Resource Name and Resource Pathspecify {userid} (note that when specifying a name in this format, the Resource Path is automatically replaced by -userid- , you must manually specify the desired form for the path parameter).
Next, create a method to create a record for a new user, for this we select the {userid} resource , and by clicking the Actions button we select Create method , specify its type - POST and click the checkmark to create it. In the settings menu that opens, in the Integration type section, you must open the Show advanced spoiler and select AWS Service Proxy . Settings:
- AWS Region indicate the region in which 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 for receiving data)
- Action Type : Use action name
- Action : PutItem (used to create a new record / overwrite the entire value with the specified key)
- Execution role : specify the role that we created in the format arn: aws: iam :: 000000000000: role / roleName
After saving these settings, you must first go to the first square of the Method Request , select True in the API Key Required item and click on the checkmark to save the settings - this is necessary to access this method from the outside using an authorization token (set up later; do not forget to do this operation for all methods!). Go back and go into the second Integration Request square to configure the request itself in DynamoDB. On the page that opens, scroll to the very bottom and open the Body Mapping Templates section , click the Add mapping template button , specify Content type : application / json, in the input field you must specify the request parameters, to create a new record use the following code:
{
"TableName": "apiData",
"Item": {
"userID": {
"S": "$input.params('userid')"
},
"parameter": {
"S": "$input.path('$.parameter')"
}
},
"ReturnValues": "ALL_OLD"
}
Here we indicate the name of the table in which we make the changes, the key is indicated first by which the data will be entered: userID , its value is taken from the userid path parameter . Data on the parameter key is taken from the request body and added to the same column in our database for the specified user. As an answer - the previous value is sent for the specified key, if it existed. If a user with that username did not exist, an empty answer will come.
All that remains for us is to check the operation of the request, 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 with the Harry Potter icon:
In the window that opens, we will need to specify the valuePath parameter is the name of the user we want to create / recreate (I recall, PutItem overwrites the entire line with the specified key), just below - specify the request body:
{
"parameter": "112233"
}
The request was successful, we received a response with an empty body without any errors!
If we switch to DynamoDB , then on the Items tab we can see the user that we just created:
To read user data, you also need to create a GET method with Action - Query within the {userid} resource , configure the integration query (remember - in this case a request to the database is still done using the POST method!) and specify the following template for body mapping:
{
"TableName": "apiData",
"KeyConditionExpression": "userID = :v1",
"ExpressionAttributeValues": {
":v1": {
"S": "$input.params('userid')"
}
}
}
If we want to change some parameter values for a specific user without changing all the other lines, then we can also use the POST method with the Action type UpdateItem and the following mapping template:
{
"TableName": "apiData",
"Key": {
"userID": {
"S": "$input.params('userid')"
}
},
"UpdateExpression": "set token_proof = :tkn",
"ExpressionAttributeValues": {
":tkn": {
"S": "$input.path('$.token')"
}
},
"ReturnValues": "UPDATED_NEW"
}
In this case, the request returns all updated data about the user in case of success, from examples - this method can be used to store appsecret_proof when authorizing the user through Facebook in your application.
In fact, all basic API usage scenarios 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 favorite Actions button in our API menu and select Deploy API . Specify:
- Deployment stage : [New Stage]
- Stage name : apiRelease (or any other)
Press Deploy and get the Invoke URL of the following form: m00000000a.execute-api.us-east-1.amazonaws.com/apiRelease . To make requests to this address - an authorization token is required, to receive it - go to the API Keys section in the menu on the left , click the Create button , name your key somehow and save it. Next, in the API Stage Association section that appears, select the desired API and the newly created scene, then click the Add button . Return through the left menu to our API, select Actions -> Deploy API , select the already created Stage and click Deploy . Voila!
Now you can make requests to your API from the outside by adding header x-api-key with your token as a value to the request . To get data about our created user, it is enough to make a 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 him in the answer! Thus, in a matter of minutes, you can create a simple API for accessing the database, with which you can test your new application or any other service that does not require a complex data structure. For more complex projects, of course, it is worth using more suitable tools.