Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set Request Validator with AWS SAM?

Tags:

aws-sam

I defined a model with JSONschema and set it to the lambda. I could see that the model was added in Request Body like the picture below

request method console picture

But I also need to set Request Validator to validate it. This is my example AWS SAM template below.

Resources:
  Api:
    Type: "AWS::Serverless::Api"
    Properties:
      StageName: !Ref Environment
      TracingEnabled: false
      EndpointConfiguration: REGIONAL
      Auth:
        Authorizers:
          Auth:
            FunctionPayloadType: TOKEN
            FunctionArn: !GetAtt Auth.Arn
            Identity:
              Header: authorization
      Models:
        RegisterCat:
          $schema: "http://json-schema.org/draft-04/hyper-schema#"
          title: RegisterCat
          type: object
          properties:
            name:
              type: string
              maxLength: 32
            species:
              type: string
              maxLength: 32
            age:
              type: integer
              minimum: 0
              maximum: 100
          required:
            - name
            - species
            - age
  RegisterCat:
    Type: "AWS::Serverless::Function"
    Properties:
      FunctionName: !Join ["-", [example, !Ref Environment, register, cat]]
      CodeUri: register_cat/
      Environment:
        Variables:
          TABLE_NAME: !Join ["-", [!Ref Environment, cat, table]]
      Policies:
        - Statement:
            - Sid: CatTable
              Effect: Allow
              Action:
                - "dynamodb:PutItem"
              Resource: !GetAtt CatTable.Arn
      Events:
        PublicApi:
          Type: Api
          Properties:
            Path: /cat/
            Method: POST
            RestApiId: !Ref Api
            RequestModel:
              Model: RegisterCat
              Required: true

I can see that there is an option to add request validator when you create method in aws cli or Cloudformation

  put-method
--rest-api-id <value>
--resource-id <value>
--http-method <value>
--authorization-type <value>
[--authorizer-id <value>]
[--api-key-required | --no-api-key-required]
[--operation-name <value>]
[--request-parameters <value>]
[--request-models <value>]
[--request-validator-id <value>]
[--authorization-scopes <value>]
[--cli-input-json <value>]
[--generate-cli-skeleton <value>]
Type: AWS::ApiGateway::Method
Properties: 
  ApiKeyRequired: Boolean
  AuthorizationScopes: 
    - String
  AuthorizationType: String
  AuthorizerId: String
  HttpMethod: String
  Integration: 
    Integration
  MethodResponses: 
    - MethodResponse
  OperationName: String
  RequestModels: 
    Key : Value
  RequestParameters: 
    Key : Value
  RequestValidatorId: String
  ResourceId: String
  RestApiId: String

I read SAM specification document in Github several times and tried setting the request validator. However I couldn't find any way to set it up with SAM. Is there a way to set the request validator on method or should I request the feature in SAM repo?

Thank you for reading my question.

like image 717
Jayground Avatar asked Jan 15 '20 02:01

Jayground


People also ask

How do I validate headers in API gateway?

Go to the Integration Request tab of your endpoint, click Mapping Templates , set Request body passthrough to never , add a mapping template for application/javascript , and click Method Request Passthrough from the dropdown next to Generate template .

How do I configure the AWS Sam CLI for Sam validation?

As with most AWS SAM CLI commands, it looks for a template. [yaml|yml] file in your current working directory by default. You can specify a different template file/location with the -t or --template option. The sam validate command requires AWS credentials to be configured.

How do I verify whether an AWS Sam template file is valid?

Verifies whether an AWS SAM template file is valid. The AWS SAM template file [default: template. [yaml|yml]]. The specific profile from your credential file that gets AWS credentials. The AWS Region to deploy to. For example, us-east-1. The path and file name of the configuration file containing default parameter values to use.

How do I configure the request validator in API gateway?

The Request Validator in API Gateway can be configured in Terraform with the resource name aws_api_gateway_request_validator. The following sections describe 3 examples of how to use the resource and its parameters.

How do I specify a different template file/location for Sam validation?

You can specify a different template file/location with the -t or --template option. The sam validate command requires AWS credentials to be configured. For more information, see Configuration and Credential Files . © 2021, Amazon Web Services, Inc. or its affiliates.


1 Answers

  1. Add a resource of type AWS::ApiGateway::Method and connect to your Api resource with RestApiId and ResourceId.
  2. Set the RequestValidatorId value to be either
    • a reference to a RequestValidator resource,
    • the id of the one you already have created somewhere else (this information wasn't in the question)

Here is an example with a RequestValidator resource. Lets start first by adding some new params (contentHandling, validateRequestBody, validatorName). And then the new resources.

Parameters:
...
  Environment:
  ...
  contentHandling:
    Type: String
  operationName:
    Type: String
    Default: testoperationName
  validatorName:
    Type: String
    Default: testvalidatorName
  validateRequestBody:
    Type: String
    Default: testvalidateRequestBody

Resources:
...
  Method:
    Type: AWS::ApiGateway::Method
    Properties:
      HttpMethod: POST
      ResourceId: !GetAtt Api.RootResourceId
      RestApiId: !Ref Api
      ...
      RequestValidatorId: !Ref MyRequestValidator
      OperationName: !Ref operationName

  RequestValidator:
    Type: AWS::ApiGateway::RequestValidator
    Properties:
      Name: !Ref validatorName
      RestApiId: !Ref Api
      ValidateRequestBody: !Ref validateRequestBody
      ValidateRequestParameters: !Ref validateRequestParameters

More info can be found here:

  • AWS::ApiGateway::Method Associated Request Validator Example (scroll down for yaml past the json )
  • AWS::ApiGateway::RequestValidator Docs
like image 176
petey Avatar answered Oct 16 '22 06:10

petey