Changing HTTP response code on API Gateway with DynamoDB integration

1

When integrating API Gateway directly to DynamoDB, is it possible to modify the HTTP Status code (not the response body, which can be transformed) from an HTTP 200 OK to an HTTP 4xx Error if there is no record found?

2 Answers
2

I had the same issue as the poster here. The accepted answer seems to me not to be the answer the to question, as it only covers cases where DDB return a 400 error. The ResourceNotFoundException will only be triggered if the query is against an Index og table that does not exists. But my issue (and I believe the original post) was how to get API Gateway to return 404 when No Rows are found based on the query. In that case DDB will return a HTTP 200 code, so the only way to determine this is to look at the response body from DDB which is empy.

I solved this in the integration mapping response template. There you can check the Count attribute in the DDB response, and modify the response code. This worked for me:

#set($inputRoot = $input.path('$'))

#if($inputRoot.Count == 0)
  #set($context.responseOverride.status = 404)
#else
    #foreach($elem in $inputRoot.Items) {
        "progress": "$elem.progress.S",
        "content_id": "$elem.content_id.S",
        "updated": "$elem.updated.S"
    }#if($foreach.hasNext),#end
    #end
 #end
Ketil
answered 2 years ago
  • I couldnt use Count, I had to compare with an empty string. Like this:

    #set($inputRoot = $input.path('$'))
    
    #if($inputRoot == "")
      #set($context.responseOverride.status = 404)
    #else
        #foreach($elem in $inputRoot.Items) {
            "progress": "$elem.progress.S",
            "content_id": "$elem.content_id.S",
            "updated": "$elem.updated.S"
        }#if($foreach.hasNext),#end
        #end
     #end
    
-1
Accepted Answer

Yes, it can be achieved by adding HTTP 4xx in the method response, and map the corresponding response from DDB (DynamoDB) to it in the integration response. Without this, all the response status code will be mapped to 200.

In your case, DDB should return HTTP 400 (ResourceNotFoundException) if no items found, as can be seen in the API reference here

You can then define a 404 in the method response, and in the integration response defining a Regex to map 400 from DDB to the 404 in method response.

To elaborate a bit more, for AWS/HTTP(s) backend integrations, API Gateway uses the HTTP status code from the backend to match against the Regex defined in each HTTP response in the integration response to determine which status code to return to the client. In case of Lambda backend, it is looking for the "errorMessage" in the response as detailed in this blog.

answered 7 years ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions