Creating the API using CloudFormation templates

Now, let's create the API using a CloudFormation template. We will not discuss the components that were already discussed in previous recipes, nor will we discuss the theory for commands that were already discussed within the CLI commands section. The complete code is available in the code files:

  1. Start to create the template with the version, description, and RestApi resource.
  2. Add the proxy resource, '{proxy+}', as follows:

MyProxyResource:
Type: AWS::ApiGateway::Resource
Properties:
RestApiId: !Ref MyRestAPI
ParentId: !GetAtt MyRestAPI.RootResourceId
PathPart: '{proxy+}'
  1. Add the Method definition, with the AWS_PROXY integration type and ANY HTTP method, as follows:
MyMethod :
Type : AWS::ApiGateway::Method
Properties:
AuthorizationType: NONE
HttpMethod: ANY
Integration:
Type: AWS_PROXY
IntegrationHttpMethod: POST
IntegrationResponses:
- StatusCode: 200
Uri:
!Sub
- 'arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/arn:aws:lambda:us-east-1:${AWS::AccountId}:function:${LAMBDA_NAME}/invocations'
- LAMBDA_NAME: !ImportValue LambdaForProxyIntegration

ResourceId: !Ref MyProxyResource
RestApiId: !Ref MyRestAPI
MethodResponses:
- StatusCode: 200
We are importing the Lambda LambdaForProxyIntegration. Therefore, the Lambda's CloudFormation template has to be executed first.
  1. Add the deployment resource in a stage: dev.
  2. Provide permission to the API to invoke the Lambda, as follows:
LambdaInvokePermission:
Type: AWS::Lambda::Permission
Properties:
FunctionName: !ImportValue LambdaForProxyIntegration
Action: 'lambda:InvokeFunction'
Principal: apigateway.amazonaws.com
SourceArn: !Sub
- arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${API_ID}/*/*/{proxy+}
- API_ID: !Ref MyRestAPI
  1. Provide an Outputs section with a sample endpoint, as follows:
Outputs:
SampleEndpoint:
Description: 'Sample Endpoint'
Value: !Sub
- https://${API_ID}.execute-api.${AWS::Region}.amazonaws.com/dev/MyApp
- API_ID: !Ref MyRestAPI
  1. Execute the create-stack command to deploy the API.

Since we are importing the Lambda LambdaForProxyIntegration, the Lambda's CloudFormation template has to be executed first. 

  1. Finally, test the API from a REST client, such as Postman (similar to what we did for the API that we created using the CLI commands). You can also use a browser for testing, which uses the GET method, as the API can accept any HTTP method.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.240.244