Building a serverless application on AWS â Part 2: Create a DynamoDB table and store data
In the first article in this series I gave you a brief example how to build a simple API and ship it to AWS. Now it's time to put more logic into the API.But⦠so far I did not explain anything what you want to build in the end. Let's change that now; here are the requirements:A user is able to upload an image. For each uploaded image three different thumbnails should be created (small, medium, large). Before doing that the uploaded image needs to be validated. Only image/jpg, image/jpeg and image/png are allowed. At any given time the user is able to check the current status of the image processing. An image can have one of the following status: waiting_for_upload, waiting_for_thumbnails, published and in case of an validation error invalid_content_type. PrerequisitesBefore you start the implementation let me give you an introduction into AWS DynamoDB first.Amazon DynamoDB is a fully managed NoSQL database service that provides fast and predictable performance with seamless scalability.One of the most important part of using a NoSQL database (AWS DynamoDB) begins before you ever put data into it; designing the table and the corresponding primary keys. AWS DynamoDB supports two types of primary keys to choose from, a Hash Key and a Hash and Range Key.A Hash Key consists of a single attribute that uniquely identifies an itemA Hash and Range Key consists of two attributes that together, uniquely identify an itemTo see both types of primary keys in action I will provide you an example of each with the writing and reading operation together with the AWS CloudFormation AWS::DynamoDB::Table resource.Example: "Hash Key" based primary key1. Write operation2. Read operation3. AWS CloudFormation resourceExample: "Hash and Range Key" based primary key1. Write operationThe difference is that you are forced to add the required "Range Key" (createdAt) in the put operation.2. Read operationThe difference is to use the query operation instead of put.3. AWS CloudFormation resourceThe difference is to define createdAt as RANGE key (Line 7-8 12-13). Let's get back to work nowâ¦So which type of primary key should you choose? Well, it depends. Do you want to store multiple items for the same ID (hash key) or is it enough to have only one item per ID (hash key)?With the requirements in mind I assume you already designed a simple entity like this:Referring to that entity the "Hash Key" based primary key is enough. The only thing we want to do is to update the status of our entity along the different processes. Therefore let's create the DynamoDB table right away. You can find the matching AWS CloudFormation resource in , Line 6-17.As you also want to store the uploaded images somewhere; I highly recommend to use AWS S3 for that. The AWS CloudFormation resource for that can be found in , Line 1-4.As soon as you created these two resources you can start to change the logic of the API.Disclaimer; AWS API Gateway has a Payload size limit of 10mb (which cannot be increased), because of that we need to find a workaround in case our user wants to upload an image which has more than 10mb in size. For that we are using an API offered by AWS S3 to generate a pre-signed URL. A "pre-signed URL" is a URL which grants the user temporary access to AWS S3, but only to one specific object in it. The pre-signed URL expires after a given time (default: 5 minutes). To be concrete: The user is doing a GET request against your API and as a response the user get an uploadUrl. In the second step the user has to do a PUT request against the uploadUrl with the image binary as payload and application/x-www-form-urlencoded as Content-Type.Let's check how this is implemented:persist initial image data with status waiting_for_upload (, Line 13-20)generate uploadUrl with help of the AWS S3 SDK (, Line 22-29)returnuploadUrl (, Line 31-35)Two last steps are missingFirst: In our updated API we are referencing two new environment variables BUCKET_NAME and IMAGE_TABLE. So we need to pass them to our application as well. To achieve that you need to change the ApiLambda resource and add Environment.Variables property. Check , Line 24-27.Second: Two new AWS services are called in your application; AWS. S3() and AWS. DynamoDB. DocumentClient(). With the existing configuration your application will fail with a PermissionDenied error. To tackle that you need to add two more policies to ApiLambdaExecutionRole resource. Check , Line 13-14.Hint: As soon as you are using a new AWS service (e. g. DynamoDb, S3, etc. ) in your application it's most likely that you have to add a new policy to your ExecutionRole in order to grant access to these services. Following this small hint saves you a lot of (debugging) time. Trust me.At any given time the user is able to check the current status of the image processing. Following this quote out of the requirements you need to setup an API route to receive the latest status of the image processing. It's easy as its sounds.Get the latest data out of AWS DynamoDB (, Line 8-20) and return it (, Line 22-27).In my next article I will explain you how to validate uploaded images and how to create thumbnails from them. That's it. Feel free to check the GitHub repository and see how it evolves through this article series. Hope I helped you a little bit in the big -serverless- world. Stay tuned!-Maik
Copyright © 2020-2035 Samuel - KingBird Home Furniture | Sitemap
OEM furniture ภาษาไทย | Custom home furniture Deutsch | Custom furniture italiano
Office furnitures manufacturer | China sofa manufacturer | Custom outdoor Furniture
{"site":{"site_id":1623,"site_type":1,"site_domain":"kingbirdfurniture.com","domain_mode":1,"original_domain":"kingbirdfurniture.com","language_code":"it","is_init_domain":0,"is_shop":false,"is_ssl":1,"lang_prefix":"/"},"page":{"page_id":60105,"page_type":"ai_article_detail","page_code":423,"page_url":"/ai-article/going-nosql-with-apsaradb-for-mongodb-or-table-store.html","page_source":"","allowAnimat":0,"content_id":4107,"content_type":5,"detail_thumb":"","detail_title":"Going NoSQL with ApsaraDB for MongoDb Or Table Store","moq":1},"translateList":{"A new item has been added to your Shopping Cart":"Un nuovo oggetto è stato aggiunto al tuo carrello","Account is not exists":"L'account non è esista","Add a review on the product":"Aggiungi una recensione sul prodotto","Add to":"Aggiungere a","Add to Cart":"Aggiungi al carrello","all":"tutti","All Orders":"Tutti gli ordini","Already commented":"Già commentato","Are you sure you want to delete it?":"Sei sicuro di voler cancellare?","Are you sure to delete the selected items?":"Sei sicuro di eliminare gli elementi selezionati?","Awaiting Payment":"In attesa del pagamento","Awaiting Shipment":"In attesa della spedizione","account security":"Sicurezza dell 'Account","address book":"rubrica","Buy":"Acquistare","Buy Now":"acquista ora","Cancel":"Annulla","Clear":"Chiaro","Clear Search":"Cancella ricerca.","Confirm":"Confermare","Choose a country":"Scegli un paese","Choose Coupon":"Scegli il coupon.","commodity payment":"pagamento delle materie prime","Completed":"completato","Condition not met":"Condizione non soddisfatta","Confirm password is inconsistent with new password":"Conferma la password è incoerente con la nuova password","Congratulations":"Congratulazioni","Congratulations! You are got a coupon.":"Congratulazioni! Hai un coupon.","Congratulations! You are got all coupons.":"Congratulazioni! Hai tutti i coupon.","Continue Shopping":"continua a fare acquisti","Copy the code and use it directly in the shopping cart.":"Copia il codice e usalo direttamente nel carrello della spesa.","Coupon List":"Elenco dei coupon","Country":"nazione","Design customization":"Personalizzazione del design.","Do not use any discount":"Non usare alcun sconto","Earliest":"Più presto","email":"e-mail","email format does not match":"Il formato e-mail non corrisponde","Estimated Delivery Time":"Tempi di consegna stimati","expired":"scaduto","Find Parts":"Trova parti","Free":"Libero","Free Quote & Information Request":"Citazione gratuita e richiesta di informazioni","Free Shipping":"Spedizione gratuita","for order over":"per ordine oltre","Get":"Ottenere","Get coupons":"Ottieni coupon","Get discount":"Scontata","Get it":"Prendilo","Get it after logging in and use it in the shopping cart.":"Prendilo dopo averlo accesso e usalo nel carrello della spesa.","Go to Page":"Vai alla pagina","Highest Price":"Il prezzo più alto","Hot Sale":"Vendita calda","home":"casa","Incorrect form format":"Formato modulo errato","inquiry":"inchiesta","Loading":"Caricamento in corso","Lowest Price":"Prezzo più basso","Match Product":"Abbinare il prodotto","Merchant Free Shipping":"Merchant Spedizione gratuita.","Most Popular":"Più popolare","my account":"il mio conto","my coupons":"i miei coupon","my inquiry":"la mia richiesta","my orders":"i miei ordini","my reviews":"Le mie recensioni","my wishlist":"La mia lista dei desideri","name":"nome","Newest":"Più recente","No Quotation":"Nessuna quotazione","No time limit":"Nessun limite di tempo","Not deleted":"Non cancellato","not valid yet":"non è ancora valido","Off":"Spento","Offers and Discounts":"Offerte e sconti","ok":"ok","optional":"opzionale","Order over":"Ordine oltre","order notes":"Note d'ordine","Password contains at least numbers and letters length should be 6-20":"La password contiene almeno numeri e lettere lettere dovrebbero essere 6-20","Password is invalid":"La password non è valida","Password length should be 6-20":"La lunghezza della password dovrebbe essere 6-20","Paypal":"Paypal","paypal payment":"Pagamento PayPal.","personal info":"informazioni personali","Please click ’click to continue’ to retry.":"Fai clic su \"Clicca per continuare\" per riprovare.","Please enter a valid email address":"Si prega di inserire un indirizzo email valido","Please enter the verification code":"Si prega di inserire il codice di verifica","Please login in first":"Per favore accedi prima","Please select attribute":"Si prega di selezionare Attributo.","Please select country/region":"Si prega di selezionare Paese / Regione","Please select superior":"Si prega di selezionare Superior","Please select the number of ratings.":"Si prega di selezionare il numero di valutazioni.","read more":"Per saperne di più","Region":"Regione","Register Success":"Registrare il successo","Sale ends in":"Vendita termina in.","Save in wishlist":"Salva nella wishlist.","Search":"Ricerca","Shipping":"spedizione","Shipping Address":"indirizzo di spedizione","shipment successful":"Spedizione riuscita","Size guide":"Guida alle taglie","Small Text":"Piccolo testo","Small Title":"Piccolo titolo","Sort By":"Ordina per","State/Province/Territory":"Stato / Provincia / Territorio","Successfully delete":"Elimina con successo","Successfully save":"Risparmi con successo","The coupon code has been copied and used in the shopping cart.":"Il codice coupon è stato copiato e utilizzato nel carrello della spesa.","The subscription is successful, thank you for your participation":"L'abbonamento ha successo, grazie per la tua partecipazione","The user center is out of service. Please contact customer service":"L'utente è fuori servizio. Si prega di contattare il servizio clienti","This is Text":"Questo è testo.","This is title":"Questo è il titolo","This transaction has failed.":"Questa transazione ha fallito.","Time to shop":"Tempo per fare acquisti","To be commented":"Essere commentato","Total":"Totale","the content can not be blank":"Il contenuto non può essere vuoto","Update password success":"Aggiorna il successo della password","Upload Image":"Carica immagine","Upload up to 6 pictures":"Carica fino a 6 immagini","uploading":"Carica","used":"Usato","user center":"Centro utente","Validity period":"Periodo di validità","valid now":"Valido ora","View Cart & Checkout":"Visualizza il carrello","Welcome to the website":"Benvenuto nel sito web","Western Union":"Western Union","Write a Review":"Scrivere una recensione","You are got a coupon.":"Hai un coupon.","You haven’t chosen an address yet":"Non hai ancora scelto un indirizzo","You haven’t selected a product yet":"Non hai ancora selezionato un prodotto","Your rating":"Il tuo punteggio","Your review":"Il tuo commento","Your shipping address error":"Il tuo errore dell'indirizzo di spedizione"}}