Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AWS API Gateway - change to 404 if query returns nothing

I have a Dynamodb table with a few fields - my_id is the PrimaryKey. In the API gateway I set up a response with a method that takes in a parameter {my_id}.

Then I have an Integration Request mapping template that takes the passed in parameter and queries the table to return all the fields that match.

Then I have an Integration response mapping template that cleans up the returned items the way I want.

This all works perfect.

The thing I can't figure out how to do is if the parameter that is passed in doesn't match anything in the table, how do I get it to change from a 200 status into a 404?

From what I can tell when the passed in parameter doesn't match anything it doesn't cause an error, it just doesn't return anything.

It seems like I need to change the mapping template on the Integration response to first check if the params are empty and then somehow tell it to change the response status.

I can find info about this type of thing with people using Lambda, but I am not using Lambda - just the Dynamodb table and the API Gateway.

like image 256
Ron Avatar asked Jun 14 '16 05:06

Ron


2 Answers

You can use Mapping Template to convert the response that you get from DDB and overrride the response code. You can get more details in the link https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-override-request-response-parameters.html

If you are using cloud formation, you can do this by using below snippet

IntegrationResponses:
  - StatusCode: "200"
    ResponseTemplates:
        application/json: |
          {
            "payload" : {
              }
            },
          }
IntegrationResponses:
  - StatusCode: "200"
    ResponseTemplates:
       application/json: |
                #set($inputRoot = $input.path('$'))
                #if($inputRoot.toString().contains("Item"))
                $input.json("$")
                #set($context.responseOverride.status = 200)
                #else
                #set($context.responseOverride.status = 404)
                #end
like image 76
Shiva Kumar Avatar answered Oct 11 '22 22:10

Shiva Kumar


Api gateway currently supports mapping the status code using the status code of the integration response (Here dynamodb response code). The only workaround is to use a lambda function which outputs different error messages that can be mapped using a error regex http://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-method-settings-execution-console.html.

like image 2
Abhigna Nagaraja Avatar answered Oct 11 '22 23:10

Abhigna Nagaraja