Adding DynamoDB to your AWS API with Lambda

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
do you want to learn how to set up a dynamodb database and connect it to your api in this video that is exactly what i'm going to show you how to do [Music] hi guys my name is sam with complete coding where our aim is to make you into the best aws and serverless developer that you can be in this video we're going to be taking the api that we built in a previous video and if you haven't watched that video i'm going to link it somewhere up here and also in the description below in that video we created an api and had a lambda for both getting some items as well as saving a cart in this video we're going to update those lambdas and add a dynamodb table which allows us to store that data in a more realistic way this also means that every time someone saves your cart to your system we can have that as a new record in our database so let's jump onto the computer and get all of that set up so now that we're back in our aws console we're going to quickly review what we did last week and then jump into adding our dynamodb tables so if we go into api gateway we can look at the api that we deployed last time which is this shopping api and what we're going to do is copy the invoke url and paste that into a browser and here we can check under roots and there are two routes there is a post cart and there is a get item by item id so at the end of our url if we add forward slash item forward slash one two three four we should get back the item the way that this returns some data is this get item is calling the integration of this and this is actually a lambda authorizer which if we click on configure is calling our get item lambda so if we click on our search terminal and search for lambda and i'm going to open this up in a new tab we can then go and look at this get item lambda in here if we look at the code section and we scroll down we can see that we get the event we have some items which are just stored in the code hard coded and then we get the item id from the path parameters and then we just get item square brackets item id which is going to return either one two three four or the data of 5 6 7 8. now this is good but what we want to do is we want to set up a dynamo table to replace this section the way that we do that is if we go into our search terminal and enter dynamo i'm going to open this in again in a new tab in here what we can do is we can click on create table and this table is going to be called shopping dash items and at the moment we're just going to have a single partition key of id if you want to be able to do querying where you can do different things then you may need to customize the partition keys and the sort keys if you're interested in that i do have another video on that but for our use case we're just going with an id partition key we're going to leave the default settings and when we get down to here i'm going to actually change it from default to customize and instead of running a provisioned instance i'm going to do on demand that means that we pay whenever our api and our database are read and written to but we don't have any ongoing costs this is good for apis that are used infrequently whereas if you're doing every second 10 different reads and writes then a provisioned instance would be better so now that we've done that we can go all the way down to the bottom and click on create table and that will create us a shopping items table whilst we're here we're also going to create one for carts so if we click create table this time it's going to be called shopping dash carts again the partition key is going to be id as we're going to be keeping this table relatively simple again in settings we're going to customize it and change it to on demand as that will be the best billing mode for us to start with and scroll all the way down to create table we can now actually see that our shopping items has been created so if we go into here at the moment there are no items in here and the way that we can see that is if we go under the items section and select our shopping items table there are no results what we can actually do is start creating some results so here if we click create item and by default it's going to come in this form which is where there is the attribute name and then the value this does work but i prefer to edit it in json so on the right hand side there is a thing which allows you to switch between jason and between a form so i'm going to go with jason and i'm going to untick this button for dynamodb json and leave it just as normal json this is something that i suspect most people will want to do as dynamodb adds some extra parameters into the structure of the json that it stores but we don't need that for our case now that we've got to this point what we want to do is go into our get lambda find our hard-coded values and actually copy that item and go back into our dynamo table and paste it in here it's done some interesting formatting so let's fix that so as always we need the id and the id for this one was a string of one two three four and as well as that we also need to make sure that we wrap all of our keys with strings and all of our strings are the double quoted strings as this is json formatted not javascript formatted so if we just replace this size is okay so the last bit is the price and the price will be a number and now we have our record so if we now click on create item this will create a new item in our database just like this what i'm going to do is i'm actually going to duplicate this item so if we click on here and under actions we click duplicate this just means we don't have to reformat everything we're going to create a new record called 5678 and we in our case we changed it from red to blue so we can do that here finally click create item and now we have two different items in our database you can do this as many times as you want with as many different parameters as you would like to get your database populated now what we need to do is update our code to get the items from here instead of getting the items from our code itself so here what we're going to do is we're going to delete this items object and delete this little bit here and instead we're going to call dynamo dot get and into this get request we're going to pass an object with a table name and this table name we're going to copy from our dynamodb tables so it is shopping items is the table we're making the request to and paste that in there and then what we have to do is we have to pass in a key object and in here we want to say that the id equals the item id that we get from our path parameters now this all looks good but one thing is that we haven't defined this dynamo case so what we need to do is at the top of our code we need to import dynamo from the aws sdk and then create that so if we say we com so if we say const aws equals require the aws sdk and that is by default already installed on every lambda now that we've imported aws we can say that const dynamo equals a new aws dot dynamodb dot document client just like that and what this is doing is it is creating our database connector it called dynamo and then we can do this get request one thing with this get request is it is going to be a asynchronous request so we need to add dot promise on the end to turn it into a promise instead of a callback based a database request and that means we also need to add a weight at the start so that we are getting back the value instead of getting back a promise now that that has all happened i need to save this file and click deploy and that will deploy our new lambda so now that we've made all the changes to the code what we need to do is make sure that this lambda has permission to read our database if we scroll up to our configuration section and then on the left there is a permissions tab at the moment we have this role which only has permission to access cloud watch logs which is where the logs end up what we want to do is actually edit this so if we click on edit we can open up our get item role and if we click on this button it will take us to the i am console where we can give it extra permissions to be able to read from dynamo so in here at the moment it only has the ability to execute a lambda but what we can do is we can either attach a policy or we can add an inline policy in my case i'm going to add an inline policy here i want to say that we can access dynamo db and in i want to say that i can do any of the read requests and under resources i could either pick a specific table so i could go down to here and add the arn of that dynamo table but for now i'm just going to click on all resources review this policy and we're going to see that dynamod dynamodb read full access is assigned to this policy so give it a name and call it dynamo full read and create that policy and now this policy has been created and it is assigned to the get item role that get item roll is available on our lambda so this all means that i can now do a request to this lambda and it is able to access dynamodb if i open up a browser and refresh this page we're now getting back a slightly different structure here when we do a get we get back an item from dynamodb and that item is the object that we've stored in there this just means that we definitely know that we are returning exactly the data from dynamodb and to prove that i can change something in one two three four so if go into items and shopping items find record one two three four change it from red to purple and save this change once this has changed we can go back into our browser refresh the page and we can see that now the color is purple and the description is a purple t-shirt that is how quickly the database updates and new data can be provided to your api so obviously this is getting an item so we want to clean this up a little bit to clean this up what we're going to do is change this from being item to being record and we are going to switch that out so here we're checking if the record exists and at the very end we want to stringify record dot item which is going to be just the data from the database if we deploy this again and now refresh our page we get a record which is exactly what we would expect to get before so that's a little extra step we need to do to clear up the data we get back from dynamodb now this is how you add data requests so we're requesting the get record from the shoppings table so we need to do something similar in the in the create cart i'm going to copy these first two lines as we're going to use those two again in the other lambda so at the top if we search for lambda one more time in here if we go to create cart we can start updating this code so if we paste those first two lines in at the top we get the body and we console log out the body and i have this comment from last time saying this is where you would add the db.right so here what we're going to do is we're going to now use dynamo dot put and the reason it is a put is this could either be a new record that we are writing to the database or it could be actually that you're updating an existing one so if you create a cart with the same name then that will be added in here the parameters for this are again a table name and i'm going to copy this from dynamodb so it is shopping carts as well as that we then need to pass up the item data so we have the item and what i'm just going to do is i'm going to pass the whole body in here now this does mean that we have to expect the user to pass up an id so i'm going to change it very slightly we're going to pass in an object that has the body but we're going to spread the parameters of the body into here all that does is it basically just copies each of the keys and values into this object i'm then going to add my own id and that for now is going to be math dot random times by a very large number and this is just one way of making a unique value and because we just want this to be a single value we want to do math dot floor so now there are no decimal places and then finally we want to do two string so we can actually test this out so if you copy all of this open up a browser console and you paste that in what you should do is you should get a random string of numbers and that is going to become our id so if i now close the console and go back to here we're going to paste in our body plus a random id now that is all done what we need to do is just make sure that we await this and add a dot promise at the end as this turns the dynamo put into an async thing that returns a promise and awaiting it makes sure that it doesn't run the next line of code until this has completed so if we save this and deploy it we need to do one more thing which is configure this to be able to write to dynamo so again in the configurations and permissions if we find our role we can open that up inside i am and as before this just has the basic i am execution role so if we add another inline policy again this time we're going to be going for a dynamo but in here we want to write and have write permissions again for now we're going to go with all resources but if you wanted to have more fine grained control you could limit it to just a specific table and if i hit review policy we can see that there is a dynamo db access policy of right so i'm going to call this dynamo dash lambda dash right and if i create this policy that is now attached to the create cart role and that create cart roll is used by this lambda so now that we've updated that role we can head over into postman and i actually have the api request from last week's video what we want to do is change the data in here a little bit so instead of it being the cart id i want to pass up the items and that is going to be an array it's going to have item one two three four a second item of one two three four and then one item of five six seven eight if we do that we can now send this request making sure that we're doing a post request to our url forward slash cart and passing up some json data if we send this we get back a 201 response with message cart created and if we go back into our aws console search for our items inside demodb and look for shopping carts i can refresh this and i actually have here a random id it has an owner of sam and items of one two three four one two three four and five six seven eight so we've managed to successfully get data from a dynamodb table as well as adding new data to that same database what we could do in a next bit is we could create a get shopping cart and what we could do is we could pass up the id which is generated into that api and we could do a get on this shopping carts table which would allow us to use those for other purposes in this video we've managed to update our existing api to add a dynamodb database to the whole infrastructure every time someone tries to do a get on an item we do a lookup in dynamo to get that item and every time they create a new cart we are saving that data to a different table in dynamo this is definitely a more realistic use case for apis and hopefully it helps you understand how you can start to use a dynamo table inside a lambda which is used for an api if you've learned something new in this video make sure to hit that thumbs up button as it really helps the channel and helps more developers just like yourselves learn about dynamodb and apis and if you haven't done already make sure to subscribe down here as we release regular content on aws and serverless
Info
Channel: Complete Coding
Views: 281
Rating: undefined out of 5
Keywords: AWS, serverless, Serverless Framework, NodeJS
Id: pp-5u6LB9K8
Channel Id: undefined
Length: 24min 39sec (1479 seconds)
Published: Mon Dec 06 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.