Skip to content

Commit 0ed746b

Browse files
committed
docs: add data model validation section
Signed-off-by: heitorlessa <[email protected]>
1 parent cb8d6a0 commit 0ed746b

File tree

1 file changed

+94
-6
lines changed

1 file changed

+94
-6
lines changed

docs/content/utilities/parser.mdx

Lines changed: 94 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -130,18 +130,106 @@ def my_function():
130130
}
131131
```
132132

133-
### Error handling
133+
### Data model validation
134134

135-
**TBW**
135+
<Note type="warning">
136+
This is radically different from the <strong>Validator utility</strong> which validates events against JSON Schema.
137+
</Note><br/>
136138

137-
## Built-in envelopes
139+
You can use parser's validator for deep inspection of object values and complex relationships.
138140

139-
**TBW**
141+
There are two types of class method decorators you can use:
140142

141-
## Extending built-in models
143+
* **`validator`** - Useful to quickly validate an individual field and its value
144+
* **`root_validator`** - Useful to validate the entire model's data
145+
146+
Keep the following in mind regardless of which decorator you end up using it:
147+
148+
* You must raise either `ValueError`, `TypeError`, or `AssertionError` when value is not compliant
149+
* You must return the value(s) itself if compliant
150+
151+
#### Validating fields
152+
153+
Quick validation to verify whether the field `message` has the value of `hello world`.
154+
155+
```python:title=deep_data_validation.py
156+
from aws_lambda_powertools.utilities.parser import parse, BaseModel, validator
157+
158+
class HelloWorldModel(BaseModel):
159+
message: str
160+
161+
@validator('message') # highlight-line
162+
def is_hello_world(cls, v):
163+
if v != "hello world":
164+
raise ValueError("Message must be hello world!")
165+
return v
166+
167+
parse(model=HelloWorldModel, event={"message": "hello universe"})
168+
```
169+
170+
If you run as-is, you should expect the following error with the message we provided in our exception:
171+
172+
```
173+
message
174+
Message must be hello world! (type=value_error)
175+
```
176+
177+
Alternatively, you can pass `'*'` as an argument for the decorator so that you can validate every value available.
178+
179+
```python:title=validate_all_field_values.py
180+
from aws_lambda_powertools.utilities.parser import parse, BaseModel, validator
181+
182+
class HelloWorldModel(BaseModel):
183+
message: str
184+
sender: str
185+
186+
@validator('*') # highlight-line
187+
def has_whitespace(cls, v):
188+
if ' ' not in v:
189+
raise ValueError("Must have whitespace...")
190+
191+
return v
192+
193+
parse(model=HelloWorldModel, event={"message": "hello universe", "sender": "universe"})
194+
```
195+
196+
#### Validating entire model
197+
198+
`root_validator` can help when you have a complex validation mechanism. For example finding whether data has been omitted, comparing field values, etc.
199+
200+
```python:title=validate_all_field_values.py
201+
from aws_lambda_powertools.utilities.parser import parse, BaseModel, validator
202+
203+
class UserModel(BaseModel):
204+
username: str
205+
password1: str
206+
password2: str
207+
208+
@root_validator
209+
def check_passwords_match(cls, values):
210+
pw1, pw2 = values.get('password1'), values.get('password2')
211+
if pw1 is not None and pw2 is not None and pw1 != pw2:
212+
raise ValueError('passwords do not match')
213+
return values
214+
215+
payload = {
216+
"username": "universe",
217+
"password1": "myp@ssword",
218+
"password2": "repeat password"
219+
}
220+
221+
parse(model=UserModel, event=payload)
222+
```
223+
224+
<Note type="info">
225+
You can read more about validating list items, reusing validators, validating raw inputs, and a lot more in <a href="https://pydantic-docs.helpmanual.io/usage/validators/">Pydantic's documentation</a>.
226+
</Note><br/>
227+
228+
229+
## Built-in envelopes
142230

143231
**TBW**
144232

145-
## Deep model validation
233+
## Extending built-in models
146234

147235
**TBW**

0 commit comments

Comments
 (0)