The AWS Serverless Application Model (SAM) CLI is a pretty slick way to start building microservices quickly. One thing I struggled with for a while was, how do I prevent bad people from accessing my API? This ended up being a bit tricky, so I came up with a basic template.yml boilerplate:

In the same directory, you’ll need a file called index.js that looks something like this:

exports.handler = function handler(event, context, callback) {

With those two files in the same folder, we can switch to the Terminal and run sam deploy --guided. After we enter the needed deploy information, you should get this:

The top URL is where you can find your API Key, and the bottom is the new API Gateway.

This simple function just returns whatever you sent to it. Here’s an example:

curl -X POST -H 'content-type: application/json' -H "x-api-key: 938ngCZFUf6nbBzOwA8F32KoMBPd8u0U1GVCCI3t" -d '{"hello","world"}'


  "resource": "/{proxy+}",
  "path": "/something/neat/",
  "httpMethod": "POST",
  "headers": {...},
  "multiValueHeaders": {...},
  "queryStringParameters": null,
  "multiValueQueryStringParameters": null,
  "pathParameters": {"proxy": "something/neat"},
  "stageVariables": null,
  "requestContext": {
    "resourceId": "asu7ip",
    "resourcePath": "/{proxy+}",
    "httpMethod": "POST",
    "extendedRequestId": ...,
    "requestTime": "06/Jul/2020:02:27:05 +0000",
    "path": "/Prod/something/neat/",
    "accounted": "...",
    "protocol": "HTTP/1.1",
    "stage": "Prod",
    "domainPrefix": "lvogzya6p7",
    "requestTimeEpoch": 1594002425141,
    "requestId": "7fdf55a2-0d95-4fd2-92e6-ded5f8481eaa",
    "identity": {...},
    "domainName": "",
    "apiId": "lvogzya6p7"
  "body": "{\"hello\",\"world\"}",
  "isBase64Encoded": false

Leave a Reply

Your email address will not be published. Required fields are marked *