[Python] Build a CRUD Serverless API with AWS Lambda, API Gateway and a DynamoDB from Scratch

preview_player
Показать описание


====== Markers =======
0:00 - Intro
0:58 - Database Creation (DynamoDB)
1:44 - Lambda Function Creation
4:13 - API Gateway Configuration
8:10 - Write the CRUD API Code in Python
21:28 - Update Lambda Code
22:02 - Test the Serverless API
Рекомендации по теме
Комментарии
Автор

I've followed about 6 videos before trying to get this working and was unsuccessful.
A couple of things I took away from yours that made it successful for me:
- Your attention to detail and explanation of the code was very helpful.
- Setting the timeout to longer than 3 seconds I think is the golden thing that puzzled me, other videos didn't advise it, yet I think it helped!
- Case sensitivity is important. I named my key productid instead of productId and had to use cloud watch to figure out why mine didn't work.
- Not only does it work, I now have a code base as well as a base understanding to keep going. Massive thank you!

billyboba
Автор

I had to add lambda/dynamodb functionality to a simple website in just a few hours and was worried I wouldn't have time, but this vid totally saved the day. Everything worked perfectly. Thanks!

dhochee
Автор

This is super helpful material. Your level of content and pace are great. Thanks a lot Felix!

shaneatvt
Автор

If you are getting internal server error then make sure that the code is correct and that dynamo table name is spelt as productId (capital I not i). If you are getting a 404 not found error then make sure you have spelt your variables correctly. I had PATCH as PACH. I've provided the code written in this tutorial below:

# lambda_function:

import boto3
import json
import logging
from custom_encoder import CustomEncoder
logger = logging.getLogger()


dynamodbTableName = "product-inventory"
dynamodb = boto3.resource("dynamodb")
table =

getMethod = "GET"
postMethod = "POST"
patchMethod = "PATCH"
deleteMethod = "DELETE"
healthPath = "/health"
productPath = "/product"
productsPath = "/products"


def lambda_handler(event, context):
logger.info(event)
httpMethod = event["httpMethod"]
path = event["path"]
if httpMethod == getMethod and path == healthPath:
response = buildResponse(200)
elif httpMethod == getMethod and path == productPath:
response =
elif httpMethod == getMethod and path == productsPath:
response = getProducts()
elif httpMethod == postMethod and path == productPath:
response =
elif httpMethod == patchMethod and path == productPath:
requestBody = json.loads(event["body"])
response = modifyProduct(requestBody["productId"], requestBody["updateKey"], requestBody["updateValue"])
elif httpMethod == deleteMethod and path == productPath:
requestBody = json.loads(event["body"])
response =
else:
response = buildResponse(404, "Not Found")
return response

def getProduct(productId):
try:
response = table.get_item(
Key={
"productId": productId
}
)
if "Item" in response:
return buildResponse(200, response["Item"])
else:
return buildResponse(404, {"Message": "ProductId: {0}s not found".format(productId)})
except:
logger.exception("Do your custom error handling here. I am just gonna log it our here!!")

def getProducts():
try:
response = table.scan()
result = response["Items"]

while "LastEvaluateKey" in response:
response =


body = {
"products": response
}
return buildResponse(200, body)
except:
logger.exception("Do your custom error handling here. I am just gonna log it our here!!")

def saveProduct(requestBody):
try:

body = {
"Operation": "SAVE",
"Message": "SUCCESS",
"Item": requestBody
}
return buildResponse(200, body)
except:
logger.exception("Do your custom error handling here. I am just gonna log it our here!!")

def modifyProduct(productId, updateKey, updateValue):
try:
response = table.update_item(
Key={
"productId": productId
},

UpdateExpression="set {0}s = :value".format(updateKey),
ExpressionAttributeValues={
":value": updateValue
},
ReturnValues="UPDATED_NEW"
)
body = {
"Operation": "UPDATE",
"Message": "SUCCESS",
"UpdatedAttributes": response
}
return buildResponse(200, body)
except:
logger.exception("Do your custom error handling here. I am just gonna log it our here!!")

def deleteProduct(productId):
try:
response = table.delete_item(
Key={
"productId": productId
},
ReturnValues="ALL_OLD"
)
body = {
"Operation": "DELETE",
"Message": "SUCCESS",
"deltedItem": response
}
return buildResponse(200, body)
except:
logger.exception("Do your custom error handling here. I am just gonna log it our here!!")


def buildResponse(statusCode, body=None):
response = {
"statusCode": statusCode,
"headers": {
"Content-Type": "application/json",
"*"
}
}

if body is not None:
response["body"] = json.dumps(body, cls=CustomEncoder)
return response




# custom_encoder:

import json

class
def default(self, obj):
if isinstance(obj, float):
return float(obj)

return json.JSONEncoder.default(self, obj)

asfandiyar
Автор

Hi bro, excellent video, in the first time, was desperate jejeje, because I changed some variables and put the wrong variables necessary for all the code, also, I could add all tests for every method that you mentioned in the video, was very interesting, because if you don't know how to check the logs in. cloud watch, or you don't the correct syntax to write the dynamodb resources, you always get and internal server error 502. Thanks for this video you won a follower for your channel. Note: I broke my brain, trying to fix all my errors, but this is our world, we try to understand other codes and to practice every day until all are excellent. thanks again and regards.🤓

daqa
Автор

Very nice start-point walkthrough video. Thanks Felix! Way to go!

ehsanarefifar
Автор

Great work, Felix Yu! You successfully explained API Gateway and Lambda in a very detailed way. Thank you.

tarcisiosteinmetz
Автор

Felix - any chance you can share the code repo??

I'm a python noob, and getting intenral server errors when hitting API GW with a 502. Source could be helpful as I troubleshoot what I've done wrong.

trevspires
Автор

Very helpful and insightful Felix. Thank you for sharing this, very much appreciated.

clivebird
Автор

Very very helpful tutorial for a beginner.. Thank you so much!

LS-qgzn
Автор

Thee best ever explanation I have saw about this subject.

JoseRodrigues-vdsi
Автор

Awesome, thanks for making this video😊

andynelson
Автор

Hi Felix, Can you please share the code because I'm getting error on my system as "Internal Server Error".
Please share code anyone.

CMishra-klrb
Автор

got error.

{
"message": "Internal server error"
}

502Bad Gateway. How to resolve this. No errors shown in the log events. Thank you.

anojamadusanka
Автор

Bro you're a Lambda Beast!!! Alteast to a mere mortal novice!!!!

kothon
Автор

Awesome Video, very helpful and the standard of code is also adorable.
one request Felix
please create a separate playlist for python aws functionalities with the same standard of coding please that would be very helpful to the mass.

SatyaNand
Автор

Thanks for making videos for nodejs and lambda function super happy for that, also could you please make videos for js, your videos are great and i want to learn aws with nodejs and not python

mukuljain
Автор

Hi getting [ERROR] KeyError: ‘httpMethod’ …. On post getting a 200 with the healthPath but the above error when trying to retrieve from an existing dynamodb

lennyc
Автор

I have a problem that when I make the query the event does not bring the httpMethod and path information, the event comes empty.

DestroidAdicted
Автор

I tried updating using patch and I am getting Internal Server Error message. Wonderful video you put up. It was very helpful

victoradejumo