I am fairly new to AWS SAM. I have implemented an API Gateway using AWS web console and specified the body validation in the API method request, I want to achieve the same thing but using SAM template. My search for how to specify Method Request in API Gateway SAM template gave nothing related to this. Any Help please?
2 Answers
Complete guide to add validations on API gateway here.
Below is a code snippet from SAM template.yaml to add body validations on a sample API. Here a PingInput API model is defined onthe /ping path on the API. The Model contains one required and one optional parameter. Calling the API without the required parameter will fail.
AuthApiGateway:
Type: AWS::Serverless::Api
Properties:
StageName: Prod
DefinitionBody:
swagger: '2.0'
info:
version: '1.0'
title: 'AwsRestServiceTemplate'
paths:
/ping:
x-amazon-apigateway-any-method:
responses: {}
post:
x-amazon-apigateway-request-validator: 'Validate body' # To specify that the Http Post body needs to be validated
parameters:
- in: 'body'
name: 'PingInput'
required: true
schema:
$ref: '#/definitions/PingInput'
x-amazon-apigateway-integration:
httpMethod: post
type: aws_proxy
uri:
Fn::Sub: arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${PingFunction.Arn}/invocations
x-amazon-apigateway-request-validators:
Validate body:
validateRequestParameters: true
validateRequestBody: true
definitions:
PingInput:
type: 'object'
required:
- 'requiredKey'
properties:
requiredKey:
type: 'string'
optionalKey:
type: 'string'
Comments
If you are looking to configure `authorization", here is the SAM template.
MyApi:
Type: AWS::Serverless::Api
Properties:
StageName: Prod
Auth:
DefaultAuthorizer: AWS_IAM
MyFunction:
Type: AWS::Serverless::Function
Properties:
FunctionName: MyFunction
...
Events:
Post:
Type: Api
Properties:
Path: /compute
Method: POST
RestApiId: !Ref MyApi
Auth:
Authorizer: AWS_IAM
You have to define the authorizer inside AWS::Serverless::Api definition and use it inside the function.
References: