mulemule-studiomulesoftramlmule4

Mule 4 - Return error if passing payload request parameter that was not defined in the raml


just to check is it possible to return an error if the user passed the parameter that was not defined in the api raml? For eg, below is my defined body payload structure in my api raml

{
  "test1": "value1",
  "test2": "value2",
  "test3": "value3"
}

and I would like to return error if the user passed any parameter that was not defined in the body payload structure above, for eg

{
  "test1": "value1",
  "test2": "value2",
  "test3": "value3",
  "4": "5"
}

Sample of RAML for discussion

#%RAML 1.0
title: Sample API
version: 1.0
/users:
    description: This is sample only
    post:
      body: 
        application/json:
          example: |
            {
           "test1": "value1",
           "test2": "value2",
           "test3": "value3"
            } 
      responses: 
        200:
          body: 
            application/json:
              example: |
                {
                "message":"This is for testing purposes"
                }

Solution

  • First you need to define the type for the body. A JSON schema may also work. An example is not an schema nor it will be used to validate inputs. Although in modern versions of MuleSoft products the example will be validated. I use the additionalProperties: false configuration for the type so the validation rejects extra attributes.

    Example:

    #%RAML 1.0
    title: Sample API
    version: 1.0
    
    types:
      test_type:
        additionalProperties: false
        type: object
        properties:
          test1:
            type: string
            required: true
          test2:
            type: string
            required: true
          test3:
            type: string
            required: true
    
    /users:
        description: This is sample only
        post:
          body: 
            application/json:
              type: test_type
              example: |
                {
                  "test1": "value1",
                  "test2": "value2",
                  "test3": "value3"
                } 
          responses: 
            200:
              body: 
                application/json:
                  example: |
                    {
                    "message":"This is for testing purposes"
                    }