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回答
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年前

ログインしていません。 ログイン 回答を投稿する。

優れた回答とは、質問に明確に答え、建設的なフィードバックを提供し、質問者の専門分野におけるスキルの向上を促すものです。

質問に答えるためのガイドライン

関連するコンテンツ