zoukankan      html  css  js  c++  java
  • [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"}`.

  • 相关阅读:
    int a=5,则 ++(a++)的值是?
    C中文件操作说明
    最大子序列和 o(n)
    括号匹配
    DOM、SAX、JDOM、DOM4J四种XML解析方法PK
    java中的trim()
    SAX解析XML
    ConcurrentHashMap完全解析(jdk6/7,8)
    为什么推荐Zookeeper作注册中心
    分布式锁的三种实现方式
  • 原文地址:https://www.cnblogs.com/Answer1215/p/14774552.html
Copyright © 2011-2022 走看看