AWS API Gateway - How do I get the date/timestamp/epoch in a body mapping template?

13k views Asked by At

I need to include the request time in the body mapping template for an API Gateway method. Is there a date/time variable or function? I couldn't find anything in the template reference.

Example body mapping template:

Action=SendMessage&MessageBody=$util.urlEncode("{""timestamp"":""TIMESTAMP_HERE"",""body-json"":$input.json('$'),""params"":""$input.params()""}")
3

There are 3 answers

6
Abhigna Nagaraja On BEST ANSWER

UPDATE: API Gateway just added two new context variables http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html

$context.requestTime    The CLF-formatted request time (dd/MMM/yyyy:HH:mm:ss +-hhmm).
$context.requestTimeEpoch   The Epoch-formatted request time.

API gateway doesn't support this currently. Its been requested before on the forums - https://forums.aws.amazon.com/thread.jspa?messageID=697658&. We have this feature in our backlog, but unfortunately I can't commit to any timelines.

1
MattC On

Just set a time value at the top of your template for the date you want it to expire. Then add that as an attribute to your Item. For example, if you want the Item to expire in 60 days, you would add 5184000 seconds.

#set($expireDate = $context.requestTimeEpoch + 5184000) 
{
  "TableName": "your-table-name",
  "Item": {
      ... other attributes
      "expireDate": {"N": "$expireDate"},
  }
}
6
Free Willaert On

There appears to be a way to get a timestamp from the API Gateway request, but you need to look in the X-Ray documentation to find it:

Amazon API Gateway gateways add a trace ID to incoming HTTP requests in a header named X-Amzn-Trace-Id.

(...)

A trace_id consists of three numbers separated by hyphens. For example, 1-58406520-a006649127e371903a2de979. This includes:

  • The version number, that is, 1.
  • The time of the original request, in Unix epoch time, in 8 hexadecimal digits. For example, 10:00AM December 2nd, 2016 PST in epoch time is 1480615200 seconds, or 58406520 in hexadecimal.

(...)