Annotation Serialization#
Basic usage#
As you already know, FastStream serializes your incoming message body according to the function type annotations using Pydantic.
So, there are some valid use cases:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |
The same applies to other Python primitive types as well (float, bool, datetime, etc.)
Note
If the incoming message cannot be serialized by the described schema, FastStream raises a pydantic.ValidationError with a correct log message.
Also, thanks to Pydantic (again), FastStream is able to serialize (and validate) more complex types like pydantic.HttpUrl, pydantic.PositiveInt, etc.
JSON Basic Serialization#
But how can we serialize a more complex message, like { "name": "John", "user_id": 1 } ?
For sure, we can serialize it as a simple dict
1 2 3 4 5 6 7 | |
But it doesn't look like a correct message validation, does it?
For this reason, FastStream supports per-argument message serialization: you can declare multiple arguments with various types and your message will be unpacked into them:
1 2 3 4 5 6 7 | |
1 2 3 4 5 6 7 | |
1 2 3 4 5 6 7 | |
1 2 3 4 5 6 7 | |
1 2 3 4 5 6 7 | |
1 2 3 4 5 6 7 | |
Tip
By default FastStream uses json.loads() to decode and json.dumps() to encode your messages. But if you prefer orjson just install it and the framework will use it automatically.
Serialization details#
Simple message#
If you expect to consume a simple message like b"1" or b"any_string", use a single argument as the function annotation.
In this case, your argument name does not matter, because it is the whole message body.
See the examples below:
1 2 | |
1 2 | |
JSON-like message#
If you expect to consume a message with a specific structure like JSON, multiple arguments are a shortcut for JSON.
In this case, your message will be unpacked and serialized by its fields.
See the examples below:
1 2 | |
To consume a single JSON object, you should create a single-field pydantic model and use it for annotation.
1 2 3 4 5 | |
Partial body consuming#
If you don't need to use all the fields, you can simply specify the fields you want to use, and the others will be ignored. See the example below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | |