AWS API Gateway - How do I get the date/timestamp/

2020-07-16 08:19发布

问题:

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()""}")

回答1:

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.



回答2:

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.

(...)