API gateway custom domain using AWS-CDK
Creating custom domains for RestApis is the best way to make sure your API or system can easily be used by 3rd parties.
This is a very useful way to identify the api-gateway URL. We also can create multiple api-gateway distributed across multiple environment.
Let's dive into the code.
Accessing api needs multiple components.
- Getting the hosted zone.
- Creating a new certificate based on the domain.
- Creating new rest api based on the domain and certificate.
- Creating a Record in route53.
- Creating a sample lambda and attaching to api gateway
import * as ec2 from 'aws-cdk-lib/aws-ec2';import { Stack } from 'aws-cdk-lib';import * as path from 'path';import * as route53Targets from 'aws-cdk-lib/aws-route53-targets';import * as lambdaNode from 'aws-cdk-lib/aws-lambda-nodejs';import * as route53 from 'aws-cdk-lib/aws-route53';import * as apigateway from 'aws-cdk-lib/aws-apigateway';import * as acm from 'aws-cdk-lib/aws-certificatemanager';export function CDKApiGateway(stack: Stack, envProps: props) {// VPC is already created.const vpc = ec2.Vpc.fromLookup(stack, 'VPC', {vpcName: `vpc`,});const hostedZone = route53.HostedZone.fromHostedZoneAttributes(stack, `route53-zone`, {zoneName: hostedZoneName!,hostedZoneId: hostedZoneId!,});const certificate = new acm.Certificate(stack, 'Certificate-api-test', {domainName: 'api.dev.**.***.com',});const api = new apigateway.RestApi(stack, 'example-custom-api-domain', {domainName: {domainName: 'api.dev.**.***.com',certificate,},});new route53.ARecord(stack, 'apiDNS-example-a-record', {zone: hostedZone,recordName: 'api.dev.**.***.com',target: route53.RecordTarget.fromAlias(new route53Targets.ApiGateway(api)),});const hello = new lambdaNode.NodejsFunction(stack, `lambda-hello`, {entry: path.join('functions/hello/src/hello.ts'),vpc,handler: 'handler',environment: {FUNCTION_NAME: 'hello',},});const top = api.root.addResource('api');const helloResource = top.addResource('hello', {defaultIntegration: new apigateway.LambdaIntegration(hello),});// Add method along with integration lambda with api gatewayhelloResource.addMethod('GET');}
No comments:
Post a Comment
If you have any doubts, Please let me know