News KrakenD Enterprise v2.6 released with OpenTelemetry, FIPS-140, gRPC server and more

Community Documentation

Recent changes

You are viewing a previous version of KrakenD Community Edition (v2.0) , go to the latest version

Validating the body with the JSON Schema integration

Document updated on May 2, 2021

KrakenD endpoints receiving a JSON object in its body can apply automatic validations using the JSON Schema vocabulary before the content passes to the backends. The json schema component allows you to define validation rules on the body, type definition, or even validate the fields’ values.

When the validation fails, KrakenD returns to the user a status code 400 (Bad Request), and only if it succeeds, the backend receives the request.

JSON Schema Configuration

The JSON Schema configuration has to be declared at the endpoint level with the namespace object validation/json-schema. KrakenD offers compatibility for the specs draft-04, draft-06 and draft-07.

The following example checks if the body is a json object:

{
    "extra_config": {
        "validation/json-schema": {
            "type": "object"
        }
    }
}

You can apply constraints by adding keywords to the schema. For instance, you can check that the type is an instance of an object, array, string, number, boolean, or null.

All the configuration inside the namespace is pure JSON Schema vocabulary. Read the JSON schema documentation to get familiar with the specification.

A full configuration for you to try on the localhost with the debug endpoint is:

{
    "version": 3,
    "port": 8080,
    "host": [ "http://127.0.0.1:8080" ],
    "endpoints": [
        {
            "endpoint": "/address",
            "method": "POST",
            "backend": [
                {
                    "url_pattern": "/__debug/"
                }
            ],
            "extra_config":{
                "validation/json-schema": {
                  "type": "object",
                  "properties": {
                    "number":      { "type": "number" },
                    "street_name": { "type": "string" },
                    "street_type": { "type": "string",
                                     "enum": ["Street", "Avenue", "Boulevard"]
                                   }
                  }
                }
            }
        }
    ]
}
Do you want to extend this example? try this other example

Scarf

Unresolved issues?

The documentation is only a piece of the help you can get! Whether you are looking for Open Source or Enterprise support, see more support channels that can help you.