When creating a lambda rest API using CDK, by default it creates a stage named prod
import * as cdk from "aws-cdk-lib";
import * as apigw from "aws-cdk-lib/aws-apigateway";
export class ApiGatewayDemo extends cdk.Stack {
constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {
super(scope, id, props);
// API Gateway REST API
const api = new apigw.LambdaRestApi(this, "Endpoint", {
proxy: false,
});
}
API URL looks like `https://api-id.execute-api.region.amazonaws.com/prod/`
Creating an API with the stage name dev
To set the stage name in AWS Lambda REST API using CDK, use the stageName
property.
import * as cdk from "aws-cdk-lib";
import * as apigw from "aws-cdk-lib/aws-apigateway";
export class ApiGatewayDemo extends cdk.Stack {
constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {
super(scope, id, props);
// API Gateway REST API
const api = new apigw.LambdaRestApi(this, "Endpoint", {
proxy: false,
deployOptions: {
stageName: "dev",
},
});
}
}
Now API URL will look like `https://api-id.execute-api.region.amazonaws.com/dev/`
The above code defines a class called
ApiGatewayDemo
which extends theStack
class from theaws-cdk-lib
library. TheStack
class represents a cloud resource stack in the AWS CloudFormation service.The
ApiGatewayDemo
class has a single constructor function, which takes three arguments:
scope
: an instance of theApp
class from theaws-cdk-lib
library. TheApp
class represents a CDK app, which is a collection of stacks and assets that can be deployed together.
id
: a string that uniquely identifies the stack within the CDK app.
props
: optional properties for the stack.Inside the constructor function, the code first calls the
super
function to call the baseStack
class's constructor function with thescope
,id
, andprops
arguments. This creates an instance of theStack
class.Next, the code creates an instance of the
LambdaRestApi
class from theaws-apigateway
library. This class represents an AWS Lambda REST API in a CDK app. TheLambdaRestApi
class takes two arguments:
this
: the currentApiGatewayDemo
instance, which is passed as the first argument to all methods in the class.
"Endpoint"
: a string that is used as the identifier for the REST API.The
LambdaRestApi
class has a single property,proxy
, which is set tofalse
in this example. This means that the REST API will not act as a proxy for another resource or service.The
LambdaRestApi
class also has adeployOptions
property, which is an object with astageName
property. ThestageName
property is set to"dev"
in this example.This sets the stage name of the REST API to
"dev"
. The stage name is used to identify a specific deployment of the API, and it is used as a suffix in the URL of the API (e.g.https://api-id.execute-api.region.amazonaws.com/dev
).
We can have multiple stages of the same API, each with its own stage name and separate URL