Skip to content

05 API Gateway

JP Barbosa edited this page Sep 24, 2022 · 9 revisions

API Gateway

Diagram

API Gateway

Create API Gateway

code ./stacks/resources/api.ts
import { Api, Stack, Table } from "@serverless-stack/resources";

type CreateApiOptions = { table: Table };

type CreateApi = (stack: Stack, options: CreateApiOptions) => Api;

export const createApi: CreateApi = (stack, { table }) => {
  const api = new Api(stack, "api", {
    defaults: {
      function: {
        environment: {
          table: table.tableName,
        },
      },
    },
    routes: {
      "GET /": "functions/results.handler",
    },
  });

  api.attachPermissions([table]);

  return api;
};

Update resources index

code ./stacks/resources/index.ts
...
export * from "./api";

Update stack

code ./stacks/MyStack.ts
...
import {
  ...
  createApi,
} from "./resources";

export function MyStack({ stack }: StackContext) {
  ...
  const api = createApi(stack, { table });

  stack.addOutputs({
    ApiEndpoint: api.url,
  });
}

Create results handler

code ./services/functions/results.ts
import { APIGatewayProxyHandlerV2 } from "aws-lambda";
import { DynamoDB } from "aws-sdk";

const dynamoDb = new DynamoDB.DocumentClient();

export const handler = async (event: APIGatewayProxyHandlerV2) => {
  const params = {
    TableName: String(process.env.table),
  };

  try {
    const result = await dynamoDb.scan(params).promise();

    const sortedResult = {
      ...result,
      Items: result.Items?.sort((a, b) => {
        return b.createdAt - a.createdAt;
      }),
    };

    return {
      statusCode: 200,
      body: JSON.stringify(sortedResult),
    };
  } catch (error) {
    return {
      statusCode: 500,
      body: JSON.stringify(error),
    };
  }
};

Deploy changes

npm start # or press ENTER to redeploy if SST is already running

Invoke API on SST Console

open https://console.sst.dev/sst-rekognition/sst-jp/local
image

Commit

git add .
git commit -m "API Gateway"

Next step

Setup React Frontend