@@ -32,12 +32,18 @@ You can define models to parse incoming events by inheriting from `BaseModel`.
32
32
33
33
``` python:title=hello_world_model.py
34
34
from aws_lambda_powertools.utilities.parser import BaseModel
35
-
36
- class HelloWorldModel (BaseModel ):
37
- message: str
38
-
39
- class NestedHelloWorldModel (BaseModel ):
40
- payload: HelloWorldModel
35
+ from typing import List, Optional
36
+
37
+ class OrderItem (BaseModel ):
38
+ id : int
39
+ quantity: int
40
+ description: str
41
+
42
+ class Order (BaseModel ):
43
+ id : int
44
+ description: str
45
+ items: List[OrderItem] # nesting models are supported
46
+ optional_field: Optional[str ] # this field may or may not be available when parsing
41
47
```
42
48
43
49
These are simply Python classes that inherit from BaseModel. ** Parser** enforces type hints declared in your model at runtime.
@@ -65,11 +71,14 @@ Use the decorator for fail fast scenarios where you want your Lambda function to
65
71
from aws_lambda_powertools.utilities.parser import parse, ModelValidationError
66
72
from aws_lambda_powertools.utilities.typing import LambdaContext
67
73
68
- @event_parser (model = HelloWorldModel)
69
- def handler (event , context : LambdaContext):
70
- pass
74
+ @event_parser (model = Order) # highlight-line
75
+ def handler (event : Order, context : LambdaContext):
76
+ print (event.id)
77
+ print (event.description)
78
+ print (event.items)
71
79
72
- handler(event = payload, context = LambdaContext()
80
+ order_items = [items for item in event.items]
81
+ ...
73
82
```
74
83
75
84
### parse function
@@ -79,17 +88,28 @@ Use this standalone function when you want more control over the data validation
79
88
``` python:title=parse_standalone_example.py
80
89
from aws_lambda_powertools.utilities.parser import parse, ModelValidationError
81
90
82
- payload = {" message" : " hello world" }
91
+ # Raw event for the Order model we've defined earlier
92
+ payload = {
93
+ " id" : 10876546789 ,
94
+ " description" : " My order" ,
95
+ " items" : [
96
+ {
97
+ " id" : 1015938732 ,
98
+ " quantity" : 1 ,
99
+ " description" : " item xpto"
100
+ }
101
+ ]
102
+ }
83
103
84
104
def my_function ():
85
105
try :
86
- parsed_payload = parse(event = payload, model = HelloWorldModel) # highlight-line
106
+ parsed_payload: Order = parse(event = payload, model = HelloWorldModel) # highlight-line
87
107
# payload dict is now parsed into our model
88
- return assert parsed_payload.message == payload[ " message " ]
108
+ return parsed_payload.items
89
109
except ModelValidationError:
90
110
return {
91
111
" status_code" : 400 ,
92
- " message" : " Invalid input "
112
+ " message" : " Invalid order "
93
113
}
94
114
```
95
115
0 commit comments