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?

AWS
专家
mhjwork
已提问 7 年前1112 查看次数
2 回答
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
已回答 2 年前
  • 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
已接受的回答

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.

已回答 7 年前

您未登录。 登录 发布回答。

一个好的回答可以清楚地解答问题和提供建设性反馈,并能促进提问者的职业发展。

回答问题的准则