File size: 10,006 Bytes
26e6f31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
---
title: Validation
description: Utility
---

<!-- markdownlint-disable MD043 -->

This utility provides JSON Schema validation for events and responses, including JMESPath support to unwrap events before validation.

## Key features

* Validate incoming event and response
* JMESPath support to unwrap events before validation applies
* Built-in envelopes to unwrap popular event sources payloads

## Getting started

???+ tip
    All examples shared in this documentation are available within the [project repository](https://github.com/aws-powertools/powertools-lambda-python/tree/develop/examples){target="_blank"}.

You can validate inbound and outbound events using [`validator` decorator](#validator-decorator).

You can also use the standalone `validate` function, if you want more control over the validation process such as handling a validation error.

???+ tip "Tip: Using JSON Schemas for the first time?"
    Check this [step-by-step tour in the official JSON Schema website](https://json-schema.org/learn/getting-started-step-by-step.html){target="_blank" rel="nofollow"}.

    We support any JSONSchema draft supported by [fastjsonschema](https://horejsek.github.io/python-fastjsonschema/){target="_blank" rel="nofollow"} library.

???+ warning
    Both `validator` decorator and `validate` standalone function expects your JSON Schema to be a **dictionary**, not a filename.

### Install

!!! info "This is not necessary if you're installing Powertools for AWS Lambda (Python) via [Lambda Layer/SAR](../index.md#lambda-layer){target="_blank"}"

Add `aws-lambda-powertools[validation]` as a dependency in your preferred tool: _e.g._, _requirements.txt_, _pyproject.toml_. This will ensure you have the required dependencies before using Validation.

### Validator decorator

**Validator** decorator is typically used to validate either inbound or functions' response.

It will fail fast with `SchemaValidationError` exception if event or response doesn't conform with given JSON Schema.

=== "getting_started_validator_decorator_function.py"

	```python hl_lines="8 27 28 42"
    --8<-- "examples/validation/src/getting_started_validator_decorator_function.py"
	```

=== "getting_started_validator_decorator_schema.py"

	```python hl_lines="10 12 17 19 24 26 28 44 46 51 53"
    --8<-- "examples/validation/src/getting_started_validator_decorator_schema.py"
	```

=== "getting_started_validator_decorator_payload.json"

    ```json
    --8<-- "examples/validation/src/getting_started_validator_decorator_payload.json"
    ```

???+ note
    It's not a requirement to validate both inbound and outbound schemas - You can either use one, or both.

### Validate function

**Validate** standalone function is typically used within the Lambda handler, or any other methods that perform data validation.

???+ info
    This function returns the validated event as a JSON object. If the schema specifies `default` values for omitted fields,
    those default values will be included in the response.

You can also gracefully handle schema validation errors by catching `SchemaValidationError` exception.

=== "getting_started_validator_standalone_function.py"

	```python hl_lines="5 16 17 26"
    --8<-- "examples/validation/src/getting_started_validator_standalone_function.py"
	```

=== "getting_started_validator_standalone_schema.py"

	```python hl_lines="7 8 10 12 17 19 24 26 28"
    --8<-- "examples/validation/src/getting_started_validator_standalone_schema.py"
	```

=== "getting_started_validator_standalone_payload.json"

    ```json
    --8<-- "examples/validation/src/getting_started_validator_standalone_payload.json"
    ```

### Unwrapping events prior to validation

You might want to validate only a portion of your event - This is what the `envelope` parameter is for.

Envelopes are [JMESPath expressions](https://jmespath.org/tutorial.html){target="_blank" rel="nofollow"} to extract a portion of JSON you want before applying JSON Schema validation.

Here is a sample custom EventBridge event, where we only validate what's inside the `detail` key:

=== "getting_started_validator_unwrapping_function.py"

	```python hl_lines="2 8 14"
    --8<-- "examples/validation/src/getting_started_validator_unwrapping_function.py"
	```

=== "getting_started_validator_unwrapping_schema.py"

	```python hl_lines="9-14 23 25 28 33 36 41 44 48 51"
    --8<-- "examples/validation/src/getting_started_validator_unwrapping_schema.py"
	```

=== "getting_started_validator_unwrapping_payload.json"

    ```json
    --8<-- "examples/validation/src/getting_started_validator_unwrapping_payload.json"
    ```
<!-- markdownlint-disable MD013 -->
This is quite powerful because you can use JMESPath Query language to extract records from [arrays](https://jmespath.org/tutorial.html#list-and-slice-projections){target="_blank" rel="nofollow"}, combine [pipe](https://jmespath.org/tutorial.html#pipe-expressions){target="_blank" rel="nofollow"} and [function expressions](https://jmespath.org/tutorial.html#functions){target="_blank" rel="nofollow"}.
<!-- markdownlint-enable MD013 -->

When combined, these features allow you to extract what you need before validating the actual payload.

### Built-in envelopes

We provide built-in envelopes to easily extract the payload from popular event sources.

=== "unwrapping_popular_event_source_function.py"

	```python hl_lines="2 9 14"
    --8<-- "examples/validation/src/unwrapping_popular_event_source_function.py"
	```

=== "unwrapping_popular_event_source_schema.py"

	```python hl_lines="7 9 12 17 20"
    --8<-- "examples/validation/src/unwrapping_popular_event_source_schema.py"
	```

=== "unwrapping_popular_event_source_payload.json"

    ```json hl_lines="12 13"
    --8<-- "examples/validation/src/unwrapping_popular_event_source_payload.json"
    ```

Here is a handy table with built-in envelopes along with their JMESPath expressions in case you want to build your own.

| Envelope                          | JMESPath expression                                           |
| --------------------------------- | ------------------------------------------------------------- |
| **`API_GATEWAY_HTTP`**            | `powertools_json(body)`                                       |
| **`API_GATEWAY_REST`**            | `powertools_json(body)`                                       |
| **`CLOUDWATCH_EVENTS_SCHEDULED`** | `detail`                                                      |
| **`CLOUDWATCH_LOGS`**             | `awslogs.powertools_base64_gzip(data)` or `powertools_json(@).logEvents[*]` |
| **`EVENTBRIDGE`**                 | `detail`                                                      |
| **`KINESIS_DATA_STREAM`**         | `Records[*].kinesis.powertools_json(powertools_base64(data))` |
| **`SNS`**                         | `Records[0].Sns.Message` or `powertools_json(@)`              |
| **`SQS`**                         | `Records[*].powertools_json(body)`                            |

## Advanced

### Validating custom formats

???+ note
    JSON Schema DRAFT 7 [has many new built-in formats](https://json-schema.org/understanding-json-schema/reference/string.html#format){target="_blank" rel="nofollow"} such as date, time, and specifically a regex format which might be a better replacement for a custom format, if you do have control over the schema.

JSON Schemas with custom formats like `awsaccountid` will fail validation. If you have these, you can pass them using `formats` parameter:

```json title="custom_json_schema_type_format.json"
{
	"accountid": {
		"format": "awsaccountid",
		"type": "string"
	}
}
```

For each format defined in a dictionary key, you must use a regex, or a function that returns a boolean to instruct the validator on how to proceed when encountering that type.

=== "custom_format_function.py"

	```python hl_lines="5 8 10 11 17 27"
    --8<-- "examples/validation/src/custom_format_function.py"
	```

=== "custom_format_schema.py"

	```python hl_lines="7 9 12 13 17 20"
    --8<-- "examples/validation/src/custom_format_schema.py"
	```

=== "custom_format_payload.json"

    ```json hl_lines="12 13"
    --8<-- "examples/validation/src/custom_format_payload.json"
    ```

### Built-in JMESPath functions

You might have events or responses that contain non-encoded JSON, where you need to decode before validating them.
<!-- markdownlint-disable-next-line MD013 -->
You can use our built-in [JMESPath functions](./jmespath_functions.md){target="_blank"} within your expressions to do exactly that to [deserialize JSON Strings](./jmespath_functions.md#powertools_json-function){target="_blank"}, [decode base64](./jmespath_functions.md#powertools_base64-function){target="_blank"}, and [decompress gzip data](./jmespath_functions.md#powertools_base64_gzip-function){target="_blank"}.

???+ info
    We use these for [built-in envelopes](#built-in-envelopes) to easily to decode and unwrap events from sources like Kinesis, CloudWatch Logs, etc.

### Validating with external references

JSON Schema [allows schemas to reference other schemas](https://json-schema.org/understanding-json-schema/structuring#dollarref) using the `$ref` keyword with a URI value. By default, `fastjsonschema` will make a HTTP request to resolve this URI.

You can use `handlers` parameter to have full control over how references schemas are fetched. This is useful when you might want to optimize caching, reducing HTTP calls, or fetching them from non-HTTP endpoints.

=== "custom_handlers.py"

	```python hl_lines="1 7 8 11"
    --8<-- "examples/validation/src/custom_handlers.py"
	```

=== "custom_handlers_parent_schema"

	```python hl_lines="1 7"
    --8<-- "examples/validation/src/custom_handlers_schema.py"
	```

=== "custom_handlers_child_schema"

    ```python hl_lines="12"
    --8<-- "examples/validation/src/custom_handlers_schema.py"
    ```

=== "custom_handlers_payload.json"

    ```json hl_lines="2"
    --8<-- "examples/validation/src/custom_handlers_payload.json"
    ```