Set up Amplify HTTP API
Using the AWS Cloud Development Kit (AWS CDK), you can configure Amplify Functions as resolvers for routes of an HTTP API powered by Amazon API Gateway.
Set up HTTP API with Lambda Function
To get started, 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",});
Then, create the corresponding handler file, amplify/functions/api-function/handler.ts
, file with the following contents:
import type { APIGatewayProxyHandlerV2 } from "aws-lambda";
export const handler: APIGatewayProxyHandlerV2 = 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 api-function!"), };};
Next, using the AWS CDK, create an HTTP API in your backend file:
import { defineBackend } from "@aws-amplify/backend";import { Stack } from "aws-cdk-lib";import { CorsHttpMethod, HttpApi, HttpMethod,} from "aws-cdk-lib/aws-apigatewayv2";import { HttpIamAuthorizer, HttpUserPoolAuthorizer,} from "aws-cdk-lib/aws-apigatewayv2-authorizers";import { HttpLambdaIntegration } from "aws-cdk-lib/aws-apigatewayv2-integrations";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 IAM authorizerconst iamAuthorizer = new HttpIamAuthorizer();
// create a User Pool authorizerconst userPoolAuthorizer = new HttpUserPoolAuthorizer( "userPoolAuth", backend.auth.resources.userPool, { userPoolClients: [backend.auth.resources.userPoolClient], });
// create a new HTTP Lambda integrationconst httpLambdaIntegration = new HttpLambdaIntegration( "LambdaIntegration", backend.myApiFunction.resources.lambda);
// create a new HTTP API with IAM as default authorizerconst httpApi = new HttpApi(apiStack, "HttpApi", { apiName: "myHttpApi", corsPreflight: { // Modify the CORS settings below to match your specific requirements allowMethods: [ CorsHttpMethod.GET, CorsHttpMethod.POST, CorsHttpMethod.PUT, CorsHttpMethod.DELETE, ], // Restrict this to domains you trust allowOrigins: ["*"], // Specify only the headers you need to allow allowHeaders: ["*"], }, createDefaultStage: true,});
// add routes to the API with a IAM authorizer and different methodshttpApi.addRoutes({ path: "/items", methods: [HttpMethod.GET, HttpMethod.PUT, HttpMethod.POST, HttpMethod.DELETE], integration: httpLambdaIntegration, authorizer: iamAuthorizer,});
// add a proxy resource path to the APIhttpApi.addRoutes({ path: "/items/{proxy+}", methods: [HttpMethod.ANY], integration: httpLambdaIntegration, authorizer: iamAuthorizer,});
// add the options method to the routehttpApi.addRoutes({ path: "/items/{proxy+}", methods: [HttpMethod.OPTIONS], integration: httpLambdaIntegration,});
// add route to the API with a User Pool authorizerhttpApi.addRoutes({ path: "/cognito-auth-path", methods: [HttpMethod.GET], integration: httpLambdaIntegration, authorizer: userPoolAuthorizer,});
// create a new IAM policy to allow Invoke access to the APIconst apiPolicy = new Policy(apiStack, "ApiPolicy", { statements: [ new PolicyStatement({ actions: ["execute-api:Invoke"], resources: [ `${httpApi.arnForExecuteApi("*", "/items")}`, `${httpApi.arnForExecuteApi("*", "/items/*")}`, `${httpApi.arnForExecuteApi("*", "/cognito-auth-path")}`, ], }), ],});
// attach the policy to the authenticated and unauthenticated IAM rolesbackend.auth.resources.authenticatedUserIamRole.attachInlinePolicy(apiPolicy);backend.auth.resources.unauthenticatedUserIamRole.attachInlinePolicy(apiPolicy);
// add outputs to the configuration filebackend.addOutput({ custom: { API: { [httpApi.httpApiName!]: { endpoint: httpApi.url, region: Stack.of(httpApi).region, apiName: httpApi.httpApiName, }, }, },});
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 src/main.ts
:
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, },});