Skip to content

Commit 0ac4d1d

Browse files
committed
Added serialization doc
1 parent 931ade8 commit 0ac4d1d

File tree

8 files changed

+149
-166
lines changed

8 files changed

+149
-166
lines changed

docs/basics/serialization.md

Whitespace-only changes.

docs/handling-response/response.md

Lines changed: 59 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,37 @@
1-
# Handling Responses
1+
## Introduction
2+
The `Serializer` class in the Ellar, is a custom class based on `pydantic` models, which provides additional functionality specific to Ellar's requirements.
23

3-
**Ellar** allows you to define the schema of your responses both for validation and documentation purposes.
4+
To use `Serializer` in Ellar, you simply need to create a class that inherits from `Serializer` and define your data model using pydantic fields.
5+
Here's an example of how you could define a serializer class for a user model:
46

5-
The response schema is defined on the HTTP method decorator and its applied
6-
to OPENAPI documentation and validation of the data returned from route handler function.
7+
```python
8+
from ellar.serializer import Serializer
9+
10+
class UserSerializer(Serializer):
11+
name: str
12+
email: str
13+
age: int
14+
15+
```
16+
17+
With this setup, you can use the `UserSerializer` class to validate incoming data and or serialize outgoing response data,
18+
ensuring that it matches the expected format before saving it to the database or returning it to the client.
19+
20+
## Handling Responses
721

8-
We'll create a third operation that will return information about a Fake user.
22+
Let's see how we can use **Serializer** as a responses schema which will help us validate out data output and also provide documentation on route function response.
923

24+
The response schema is defined on the HTTP method decorator.
25+
26+
For example:
1027
```python
1128
# project_name/apps/items/controllers.py
1229

1330
from ellar.serializer import Serializer
1431
from ellar.common import Controller, get
1532
from ellar.core import ControllerBase
1633

34+
# Define a User class with username, email, first_name, and last_name attributes
1735
class User:
1836
def __init__(self, username: str, email:str=None, first_name:str=None, last_name:str=None) -> None:
1937
self.username = username
@@ -27,25 +45,54 @@ class User:
2745
assert self.first_name and self.last_name
2846
return f'{self.first_name} {self.last_name}'
2947

30-
48+
# Define a Serializer class to validate response data
3149
class UserSchema(Serializer):
3250
username: str
3351
email: str = None
3452
first_name: str = None
3553
last_name: str = None
3654

37-
55+
# Create a fake user object
3856
current_user = User(username='ellar', email='ellar@example.com', first_name='ellar', last_name='asgi')
3957

40-
58+
# Define an endpoint that returns the fake user's information
4159
@Controller
4260
class ItemsController(ControllerBase):
4361
@get("/me", response=UserSchema)
4462
def me(self):
4563
return current_user
64+
4665
```
66+
This code sets up a User model and a `UserSerializer` class based on the `Serializer` class.
67+
The User model represents a user with a `username`, `email`, `first_name`, and `last_name`.
68+
The `UserSerializer` class is used to define the expected format of the response data in the `/me` endpoint.
69+
70+
When the `/me` endpoint is called, it returns the `current_user` object as the response.
71+
The `UserSerializer` is then used to parse and validate the `current_user` object, converting it into a dictionary representation
72+
that can be easily serialized to JSON.
73+
The resulting dictionary is then passed to the [`JSONResponseModel`](./response-model/#jsonresponsemodel) for serialization to a
74+
JSON string and sending the response to the client.
75+
76+
## Using Dataclass as Response Schema
77+
We can utilize the `dataclasses` feature as a response schema by utilizing the `DataclassSerializer` a base class.
4778

48-
This will convert the `User` object into a dictionary of only the defined fields.
79+
For instance, we can convert the `UserSchema` to a dataclass by defining `UserDataclass` as follows:
80+
81+
```python
82+
from dataclasses import dataclass
83+
from ellar.serializer import DataclassSerializer
84+
85+
86+
@dataclass
87+
class UserDataclass(DataclassSerializer):
88+
username: str
89+
email: str = None
90+
first_name: str = None
91+
last_name: str = None
92+
93+
```
94+
95+
By replacing the `UserSchema` with `UserDataclass`, we can expect the same outcomes in the returned response, response validation, and documentation.
4996

5097
### Multiple Response Types
5198

@@ -112,6 +159,7 @@ Here, the `response` parameter takes a KeyValuePair of the `status` and response
112159
Note that we returned a tuple of status code and response data (`403, {"message": "Please sign in first"}`) to specify the response validation to use.
113160

114161

162+
115163
## Using Response Type/Object As Response
116164

117165
You can use `Response` type to change the format of data returned from endpoint functions.
@@ -155,3 +203,5 @@ class ItemsController(ControllerBase):
155203
def me(self):
156204
return PlainTextResponse("some text response.", status_code=200)
157205
```
206+
207+
## using serialize_object function

0 commit comments

Comments
 (0)