Set up Amplify REST API
Using the AWS Cloud Development Kit (AWS CDK), you can configure Amplify Functions as resolvers for routes of a REST API powered by Amazon API Gateway.
Set up REST API with Lambda Function
Create a new directory and a resource file, amplify/functions/api-function/resource.ts
. Then, define the function with defineFunction
:
import { defineFunction } from "@aws-amplify/backend";
export const myApiFunction = defineFunction({ name: "api-function",});
Create the corresponding handler file, amplify/functions/api-function/handler.ts
, file with the following contents:
import type { APIGatewayProxyHandler } from "aws-lambda";
export const handler: APIGatewayProxyHandler = async (event) => { console.log("event", event); return { statusCode: 200, // Modify the CORS settings below to match your specific requirements headers: { "Access-Control-Allow-Origin": "*", // Restrict this to domains you trust "Access-Control-Allow-Headers": "*", // Specify only the headers you need to allow }, body: JSON.stringify("Hello from myFunction!"), };};
Use the AWS CDK to create an REST API resource powered by Amazon API Gateway.
import { defineBackend } from "@aws-amplify/backend";import { Stack } from "aws-cdk-lib";import { AuthorizationType, CognitoUserPoolsAuthorizer, Cors, LambdaIntegration, RestApi,} from "aws-cdk-lib/aws-apigateway";import { Policy, PolicyStatement } from "aws-cdk-lib/aws-iam";import { myApiFunction } from "./functions/api-function/resource";import { auth } from "./auth/resource";import { data } from "./data/resource";
const backend = defineBackend({ auth, data, myApiFunction,});
// create a new API stackconst apiStack = backend.createStack("api-stack");
// create a new REST APIconst myRestApi = new RestApi(apiStack, "RestApi", { restApiName: "myRestApi", deploy: true, deployOptions: { stageName: "dev", }, defaultCorsPreflightOptions: { allowOrigins: Cors.ALL_ORIGINS, // Restrict this to domains you trust allowMethods: Cors.ALL_METHODS, // Specify only the methods you need to allow allowHeaders: Cors.DEFAULT_HEADERS, // Specify only the headers you need to allow },});
// create a new Lambda integrationconst lambdaIntegration = new LambdaIntegration( backend.myApiFunction.resources.lambda);
// create a new resource path with IAM authorizationconst itemsPath = myRestApi.root.addResource("items", { defaultMethodOptions: { authorizationType: AuthorizationType.IAM, },});
// add methods you would like to create to the resource pathitemsPath.addMethod("GET", lambdaIntegration);itemsPath.addMethod("POST", lambdaIntegration);itemsPath.addMethod("DELETE", lambdaIntegration);itemsPath.addMethod("PUT", lambdaIntegration);
// add a proxy resource path to the APIitemsPath.addProxy({ anyMethod: true, defaultIntegration: lambdaIntegration,});
// create a new Cognito User Pools authorizerconst cognitoAuth = new CognitoUserPoolsAuthorizer(apiStack, "CognitoAuth", { cognitoUserPools: [backend.auth.resources.userPool],});
// create a new resource path with Cognito authorizationconst booksPath = myRestApi.root.addResource("cognito-auth-path");booksPath.addMethod("GET", lambdaIntegration, { authorizationType: AuthorizationType.COGNITO, authorizer: cognitoAuth,});
// create a new IAM policy to allow Invoke access to the APIconst apiRestPolicy = new Policy(apiStack, "RestApiPolicy", { statements: [ new PolicyStatement({ actions: ["execute-api:Invoke"], resources: [ `${myRestApi.arnForExecuteApi("*", "/items", "dev")}`, `${myRestApi.arnForExecuteApi("*", "/items/*", "dev")}`, `${myRestApi.arnForExecuteApi("*", "/cognito-auth-path", "dev")}`, ], }), ],});
// attach the policy to the authenticated and unauthenticated IAM rolesbackend.auth.resources.authenticatedUserIamRole.attachInlinePolicy( apiRestPolicy);backend.auth.resources.unauthenticatedUserIamRole.attachInlinePolicy( apiRestPolicy);
// add outputs to the configuration filebackend.addOutput({ custom: { API: { [myRestApi.restApiName]: { endpoint: myRestApi.url, region: Stack.of(myRestApi).region, apiName: myRestApi.restApiName, }, }, },});
Install Amplify Libraries
Use the package manager of your choice to install the Amplify JavaScript library. For example, with npm
:
npm add aws-amplify
Initialize Amplify API
To initialize the Amplify API category you need to configure Amplify with Amplify.configure()
.
Import and load the configuration file in your app. It's recommended you add the Amplify configuration step to your app's root entry point. For example index.js
in React or main.ts
in Angular.
import { Amplify } from 'aws-amplify';import outputs from '@/amplify_outputs.json';
Amplify.configure(outputs);const existingConfig = Amplify.getConfig();Amplify.configure({ ...existingConfig, API: { ...existingConfig.API, REST: outputs.custom.API, },});