[AWS] Using APIGateway to validate API request

The logic is following:

When APIGateway get a request, will check it against a JSON schema, if it failed, return 400, otherwise forward to Lambda.

Read: https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-method-request-validation.html

Work with serverless

Previously need to install plugins, but now validation is built-in function.

serverless.yml:

service:
  name: serverless-udagram-app

plugins:
  - serverless-webpack

provider:
  name: aws
  runtime: nodejs14.x

  stage: ${opt:stage, 'dev'}
  region: ${opt:region, 'us-east-1'}

  environment:
    GROUPS_TABLE: Groups-${self:provider.stage}

  iamRoleStatements:
    - Effect: Allow
      Action:
        - dynamodb:Scan
        - dynamodb:PutItem
      Resource: arn:aws:dynamodb:${self:provider.region}:*:table/${self:provider.environment.GROUPS_TABLE}

functions:
  GetGroups:
    handler: src/lambda/http/getGroups.handler
    events:
      - http:
          method: get
          path: groups
          cors: true
  CreateGroup:
    handler: src/lambda/http/createGroup.handler
    events:
      - http:
          method: post
          path: groups
          cors: true
          reqValidatorName: RequestBodyValidator
          request:
            schema:
              application/json: ${file(models/create-group-request.json)}

resources:
  Resources:
    GroupsDynamoDBTable:
      Type: AWS::DynamoDB::Table
      Properties:
        AttributeDefinitions:
          - AttributeName: id
            AttributeType: S
        KeySchema:
          - AttributeName: id
            KeyType: HASH
        BillingMode: PAY_PER_REQUEST
        TableName: ${self:provider.environment.GROUPS_TABLE}

models/create-group-request.json:

{
  "$schema": "http://json-schema.org/draft-04/schema",
  "title": "group",
  "type": "object",
  "properties": {
    "name": {
      "type": "string"
    },
    "description": {
      "type": "string"
    }
  },
  "required": ["name", "description"],
  "additionalProperties": false
}

So it checks "name" & "description" should both be string type, if you send number or other type, it return 400 error `{"message": "Invalid request body"}`.

原文地址:https://www.cnblogs.com/Answer1215/p/14774552.html