Page updated Mar 26, 2024

REST API

Under active development: The addOutput method for Amplify Gen 2 is under active development. The experience may change between versions of @aws-amplify/backend. Try it out and provide feedback at https://github.com/aws-amplify/amplify-backend/issues/new/choose

Amplify provides APIs to invoke your endpoints from your web apps. The following is an example utilizing the AWS Cloud Development Kit (AWS CDK) to add a REST API resource powered by API Gateway.

Create a Function with the following.

amplify/functions/my-function/handler.ts
1import type { APIGatewayProxyHandlerV2 } from "aws-lambda";
2
3export const handler: APIGatewayProxyHandlerV2 = async (event) => {
4 console.log("event", event);
5 return {
6 statusCode: 200,
7 headers: {
8 "Access-Control-Allow-Origin": "*",
9 "Access-Control-Allow-Headers": "*",
10 },
11 body: JSON.stringify("Hello from myFunction!"),
12 };
13};

Lets create API Gateway REST API with AWS Lambda proxy integration using AWS CDK and add the function.

amplify/backend.ts
1import { myFunction } from "./functions/my-function/resource";
2import { LambdaRestApi } from "aws-cdk-lib/aws-apigateway";
3
4const backend = defineBackend({
5 auth,
6 data,
7 myFunction
8});
9
10const apiGatewayStack = backend.createStack("apigateway-stack");
11
12// create a REST API resource
13const myAPI = new LambdaRestApi(apiGatewayStack, "MyApi", {
14 handler: backend.myFunction.resources.lambda,
15});
16
17// patch the custom REST API resource to the expected output configuration
18backend.addOutput({
19 custom: {
20 apiId: myAPI.restApiId,
21 apiEndpoint: myAPI.url,
22 apiName: myAPI.restApiName,
23 apiRegion: Stack.of(apiGatewayStack).region,
24 },
25});

Initialize REST API

To initialize the REST API you need to configure Amplify with Amplify.configure()

pages/index.tsx
1import { Amplify } from 'aws-amplify';
2import amplifyconfig from './src/amplifyconfiguration.json';
3Amplify.configure(amplifyconfig):
4
5const existingConfig = Amplify.getConfig();
6
7Amplify.configure({
8 ...existingConfig,
9 API: {
10 REST: {
11 [amplifyconfig.custom.apiName]: {
12 endpoint: amplifyconfig.custom.apiEndpoint,
13 region: amplifyconfig.custom.apiRegion,
14 },
15 },
16 },
17});

Working with REST API

Refer to the Amplify REST API documentation to learn how to work with REST API in your web app.

References

Amazon API Gateway Construct Library