Skip to content

Latest commit

 

History

History
 
 

validation-simple

Validate Requests and Responses against OpenAPI

Membrane can validate requests and responses against OpenAPI descriptions. The specifications can be in YAML or JSON format, on disk or reachable over the network.

Running the example

Use Membrane version 5 or newer.

  1. Go to the examples/openapi/validation-simple directory

  2. Start Membrane:

./service-proxy.sh

or:

service.proxy.bat
  1. Send a request using curl:
curl -X POST http://localhost:2000/persons \
  -H "Content-Type: application/json" \
  -d '{"name": "Johannes Gutenberg","age": 78}'

As the request is exactly as specified in the OpenAPI you should get the answer from the backend:

{
  "success" : true
}
  1. Now send an invalid request:
curl -X POST http://localhost:2000/persons \
  -H "Content-Type: application/json" \
  -d '{"name": "Johannes Gutenberg","age": -10}'
  1. Have a look at the validation error in the response.
{
  "method" : "POST",
  "uriTemplate" : "/persons",
  "path" : "/persons",
  "validationErrors" : {
    "REQUEST/BODY#/age" : [ {
      "message" : "-10 is smaller than the minimum of 0",
      "complexType" : "Person",
      "schemaType" : "integer"
    } ]
  }
}

You can also execute the requests in the requests.http file.

How it works

  1. In the proxies.xml configuration there is an OpenAPIProxy that reads the OpenAPI document and creates the APIs in Membrane.
<api port="2000">
    <openapi location="contacts-api-v1.yml" validate="requests"/>
</api>
  1. Have a look at the OpenAPI document contacts-api-v1.yml. The age property must be 0 or higher.
age:
  type: integer
  minimum: 0
  1. Incoming requests are validated against the definitions in the OpenAPI specification. How things evolve is dependent on the result of the validation.

a.) There are no validation errors

The request is sent to the backend with the address from the OpenAPI definition:

info:
  ...
servers:
  - url: http://localhost:3000

Then Membrane routes the answer of the backend back to the client.

b.) There are validation errors

In case of a validation failure an error message is returned to client without calling the backend.

{
  "method" : "POST",
  "uriTemplate" : "/persons",
  "path" : "/persons",
  "validationErrors" : {
    "REQUEST/BODY#/age" : [ {
      "message" : "-10 is smaller than the minimum of 0",
      "complexType" : "Person",
      "schemaType" : "integer"
    } ]
  }
}

See the openapi-validation folder for a more detailed example.


See: