AWS API Gateway: Path Parameters

Intro

We are in the process of creating a simple application that will compare user data to learn API Gateway, Lambda and DynamoDB. Part of this application is going to be the ability to request a single users data, or all of the users data at once. Instead of making two different routes we are going to add a variable to the end of the route we already have.

Creating A Variable Path Parameter

It’s really simple, we just add a set of brackets around the path parameter if we want it to be a variable.

variable path parameter

We are calling this {type} although you could call it whatever you want, we just have to reference it later.

And then we can add a GET method to this new variable route. Let’s go ahead and link that up to a new Lambda function

index.js
exports.handler = (event, context, callback) => {
  const type = event.type

  // app will request all user data or single user data
  if (type === "all") {
    callback(null, "Requested All User Data")
  } else if (type === "single") {
    callback(null, "Requested Single User Data")
  } else {
    callback(null, "Invalid Type Request in URL Parameter")
  }
}

We can see that we start by extracting type from the event, and then we just make a simple if statement to give us some different options on the “type”. We could also use a switch statement for this. Eventually the code in these sections is going to contain requests to DynamoDB, but for the time being we can just return a string while we scaffold out the rest of this request.

Map URL Variable

The next thing that we need to do is map the variable in the URL to the type key, since we are referencing that in our Lambda function.

If we check out list of $input Variables

📘 AWS Docs: Amazon API Gateway > $input Variables

We can see that $input.params(x) returns the value of a method request parameter from the path.

Therefore we can use the following in our JSON mapping file

{
    "type": "$input.params('type')"
}

Note that in this instance we have wrapped the entire $input.params() in quotation marks because we need to convert that to a string in the mapping phase. If we fail to do this we will get an error.

error
{"message": "Could not parse request body into json: 
Could not parse payload into json: Unrecognized token \'else\': 
was expecting (\'true\', \'false\' or \'null\')\n at 
[Source: (byte[])\"{\n    \"type\": else\n}\"; line: 2, column: 18]"}

And if we test that we can see that we are successfully passing the URL variable into our Lambda function as a string.

correct response from Lambda