How to give HTTP API or REST API with Lambda, the ability to not update?

So I have a Lambda Function with the code below, which is triggered by an API (AWS API Gateway).

import json

def lambda_handler(event, context):
    testString = "foo"
    if "f" in testString:
        return {
            "statusCode": 200,
            "body": json.dumps(testString)
        }

I tested it with both a HTTP API and a REST API. Because the condition returns True, in both cases the output is "foo" as it should be. But what happens if testString suddenly changes to "goo", and the condition returns False? I would like the output to remain as it previously was (not update), so it remains "foo". But when this happens, the HTTP API outputs null, and the REST API outputs {"message": "Internal server error"}.

Maybe I just need to figure out the missing piece in the code below:

import json

def lambda_handler(event, context):
    testString = "goo"
    if "f" in testString:
        return {
            "statusCode": 200,
            "body": json.dumps(testString)
        }
    else:
        #missing piece: make output not change

This is probably the first time, I have tried "creating" APIs tbh. What am I missing?

>Solution :

I would like the output t remain as it previously was (not update), so it remains "foo"

You can’t do this with just only a lambda function. You have to store your previous outputs externally, e.g. in a DynamoDB. Then your function will always be able to look up the last correct result and return it instead some random error message or incorrect answer.

Leave a Reply