Let's create the same API that we created in the previous recipe, but do it by using a CloudFormation template, and then deploy it using the AWS CLI. Finally, we will invoke the API from a browser. The CLI commands corresponding to the CloudFormation template components were already discussed in the previous recipe:
- Start by defining the template with AWSTemplateFormatVersion and a description, as follows:
---
AWSTemplateFormatVersion: '2010-09-09'
Description: Building API with AWS CloudFormation
- Define our REST API with the resource type AWS::ApiGateway::RestApi, as follows:
Resources:
MyFirstRestAPI:
Type: AWS::ApiGateway::RestApi
Properties:
Name: Greeting API
Description: API for greeting an user
FailOnWarnings: true
- Define the parent resource, greeting, under the root path, using the type AWS::ApiGateway::Resource:
GreetingResource:
Type: AWS::ApiGateway::Resource
Properties:
RestApiId: !Ref MyFirstRestAPI
ParentId: !GetAtt MyFirstRestAPI.RootResourceId
PathPart: 'greeting'
- Define a path parameter resource under greeting by using the type AWS::ApiGateway::Resource:
NamePathParamResource:
Type: AWS::ApiGateway::Resource
Properties:
RestApiId: !Ref MyFirstRestAPI
ParentId: !Ref GreetingResource
PathPart: '{name}'
- Create the method configuration with the resource type AWS::ApiGateway::Method, as follows:
MyMockMethod:
Type: AWS::ApiGateway::Method
Properties:
AuthorizationType: NONE
HttpMethod: GET
Integration:
Type: MOCK
IntegrationHttpMethod: GET
IntegrationResponses:
- StatusCode: 200
ResponseTemplates:
application/json: "{"message": "Hello $input.params('name')" }"
RequestTemplates:
application/json: "{"statusCode": 200}"
ResourceId: !Ref NamePathParamResource
RestApiId: !Ref MyFirstRestAPI
MethodResponses:
- StatusCode: 200
The CloudFormation template combines multiple CLI commands (put-method, put-method-response, put-integration, and put-integration-response) into a single and simple configuration.
- Deploy our application using the resource type AWS::ApiGateway::Deployment, as follows:
MyFirstDeployment:
DependsOn: MyMockMethod
Type: AWS::ApiGateway::Deployment
Properties:
Description: 'First Deployment'
RestApiId: !Ref MyFirstRestAPI
StageDescription:
Description: 'Dev Stage'
StageName: 'dev'
We have to specify that our Deployment resource depends on our Method resource, by using DependsOn. Otherwise, the Deployment resource may be executed before the Method resource.
- Add an Outputs section to return the final URL for our REST API:
Outputs:
SampleEndpoint:
Description: 'Sample Endpoint'
Value: !Sub
- https://${API_ID}.execute-api.${AWS::Region}.amazonaws.com/dev/greeting/Heartin
- API_ID: !Ref MyFirstRestAPI
Here, we use the intrinsic function Sub to create the final endpoint, using the pseudo-variable AWS::Region and the intrinsic function Ref.
- Create a cloudformation stack with our template, as follows:
aws cloudformation create-stack
--stack-name myteststack
--template-body file://your-first-rest-api-with-api-gateway-cf.yml
--region us-east-1
--profile admin
Here, I have used the template-body option to read the template file from the local machine. You can use the template-url option to read the template file from an S3 bucket.
The create-stack command will immediately return a stack-id, which we can use to check the stack creation status and delete the stack. We can also use the stack names for these operations:
- Check the status of the stack creation by using the describe-stacks sub-command, until it shows CREATE_COMPLETE:
aws cloudformation describe-stacks
--stack-name myteststack
--region us-east-1
--profile admin
The describe-stacks command returns the current status of the stack (for example, CREATE_IN_PROGRESS, CREATE_COMPLETE, or DELETE_COMPLETE). If the stack creation completes successfully, it will return a status of <sphttps://packt-type-cloud.s3.amazonaws.com/uploads/sites/2819/2019/01/86d4cc9e-1a66-4aa3-ba42-f0d5dc363b52.pngan>CREATE_COMPLETE, along with the Outputs section with our sample URL:
You can verify the API by going to the URL in a browser. It should print the message Hello Heartin, as follows:
- You can delete the stack, and all of the resources that it created will automatically be cleaned up:
aws cloudformation delete-stack
--stack-name myteststack
--region us-east-1
--profile admin