Server-less APIs on AWS in 15 minutes

Amazon Web Services allow you to very quickly make prototyping simple web applications and write API, for example, for a simple mobile application in a few minutes. We will use a bunch of DynamoDB and API Gateway (without Lambda functions!) to configure the GET and POST requests to the database with the ability to read, write and modify data in it.



First of all, you need to subscribe AWS and login to the console. The creation of our service we start with a database DynamoDB, click Create table, enter the name of the table apiData (in the guide I will use their names, you can specify any other), primary key by which it will be added to the record: userID and check Use default settings.


In DynamoDB lines are added to the table at the specified key, it is possible to add any number of parameters and not necessarily the match of data structure for different keys. In our case, for each user for the specified userID, we can add any data describing this user.

Next we need to create a so-called role in the service Identity and Access Management. In the menu on the left, select Roles, and then click Create new role; the name — dynamoAPI, and after clicking Next Step — in the section AWS Service Roles select Amazon API Gateway, then double-click the Next Step and finally Create Role.

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


In the Policy Generator, click Select on the next page, select your service Amazon DynamoDB and specify the following Actions:

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

You might want to be able to do any other actions with using your API, in this case — can learn their on this page for basic operations we mentioned will be enough for the eyes. As for Amazon Resource Name — here you can either specify the ARN of your table (located on the tab Overview), or you can specify * that will allow a user with the created role to have access to all tables in your account. Click Add Statement and Next Step on the page Apply Policy. This role configuration is complete!

Then create the API using API Gateway. Press the blue button Create API, on the opened page, specify its name — The API and click Create API at the bottom of the page. Now we need to create a resource that you can query, click Actions and select Create Resource.


Let's call this resource is user, it will contain information about users, and to gain access to a specific user, specify the user ID as a path parameter. To the API service Gateway to establish such parameters, we need to create a new resource at a lower level have already created a user, and as a Resource Name and Resource Path to specify {userid} (please note that if you specify a name in this format a Resource Path automaton is replaced with userid, you have to specify the desired shape for the path parameter).


Next create a method to create a record of the new user, select the share {userid}, and clicking Actions choose Create method, the type POST and press the check mark to create it. In the menu settings in the section Integration type, you must open the spoiler Show advanced and choose AWS Service Proxy. Settings:
the

    AWS Region specify the region in which your database (default is us-east-1, check it in the section Overview of your table)

    AWS Service DynamoDB

    AWS Subdomain leave blank

    HTTP method - POST (used for all calls to DynamoDB, including to obtain data)

    Action Type: Use action name

    Action: PutItem (used to create a new record/rewrite the entire value at the specified key)

    Execution role: to specify the role that we have created, in the format arn:aws:iam::000000000000:role/roleName





After saving these settings, you need to first go to the first square Request Method, API Key is Required select true and click the check mark to save the settings — this is required to access this method externally by using the authorization token (will configure later; don't forget to do this operation for all methods!). Go back and take the second square Integration Request to configure the actual query in DynamoDB. On the next page — scroll to the bottom and click Body Mapping Templates, click Add mapping template, enter Content type: application/json, the input field must specify the query parameters, to create a new record, use the following code:

the
{ 
"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 changes of the first, you specify the key by which the data will be made: userID, its value is taken from the parameter userid. Of request body data is obtained by the key parameter and added to the column and database for the specified user. As the response is sent to the previous value at the specified key if it existed. If a user with this username did not exist — will come empty response.

All we can do is to test the query 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 icon of Harry Potter:


In the opened window we need to specify a value for Path parameter is the name of the user that we want to create / recreate (remember, PutItem rewrites the entire string at the specified key), just below — specify the body of the request:

the
{
"parameter": "112233"
}

The request was successful, we received a response with an empty body without any errors!



If we go into DynamoDB tab of the Items can see the user you just created:


Read user data — it is also necessary within the resource {userid} to create a GET method c Action Query, to adjust the settings of the integration request (remember — in this case, the query to the database is still being done POST method!) and specify the following template for body mapping:

the
{
"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 other lines, we also can use POST method c Action UpdateItem and the next template mapping:

the
{
"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 query returns all the updated data about the user in case of success, see, for example, you can use this method to store the appsecret_proof with user authorization using Facebook in your app.

In fact, all the basic scenarios for using the API you can create based on these examples. All that remains for us is to access the API from outside, it is necessary to press our favorite button Actions in the menu API and choose Deploy API. Pointing:
the

    Deployment stage: [New Stage]

    Stage name: apiRelease (or any other)


Click Deploy and receive Invoke URL of the form: m00000000a.execute-api.us-east-1.amazonaws.com/apiRelease. To make requests to this address — required authorization token, in the left menu, go to API Keys, click Create, name is somehow your key and save it. In the appeared section API Stage Association select API and newly created scene, click after the Add. Go through the left menu in our API, select Actions -> Deploy API, the Stage, and click Deploy. Voila!

Now you can make requests to your API from the outside in, adding to the query header is x-api-key with your token as the value. To get information about our created user, it is sufficient to make the appropriate GET request to the address m00000000a.execute-api.us-east-1.amazonaws.com/apiRelease/user/newUserOne and you will get all information available about it. Thus, in a matter of minutes, you can create a simple API for database access, which you can use to test your new application, or any other service that does not require complex data structures. For more complex projects, of course, is to use more suitable tools.
Article based on information from habrahabr.ru

Комментарии

Популярные сообщения из этого блога

Automatically create Liquibase migrations for PostgreSQL

Looking for books as you want

Vkontakte sync with address book for iPhone. How it was done