-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathschemas.py
More file actions
40 lines (30 loc) · 1.47 KB
/
Copy pathschemas.py
File metadata and controls
40 lines (30 loc) · 1.47 KB
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
# Request - Response validation
from typing import Optional
from pydantic import BaseModel, EmailStr, Field, model_validator
# it is to validate incoming JSON request body
class UserCreate(BaseModel):
name: str = Field(min_length = 3, max_length = 30)
email: EmailStr # EmailStr is already highly specialized pre-validated type
age: int = Field(gt = 0, lt = 100) # gt -> greater than , lt -> less than
class UserResponse(UserCreate):
id: int
class Config:
from_attributes = True
# After API route finishes running, it returns an ORM object, if return is specified.
# from_attributes = True, tells pydantic not to crash and process it if it gets ORM object
# to validate instead of python dictionary
# for PUT - full update, all fields are required (same as UserCreate)
class UserUpdate(UserCreate):
pass
# for PATCH - partial update, all fields are optional
class UserPatch(BaseModel):
name: Optional[str] = Field(default = None, min_length = 3, max_length = 30)
email: Optional[EmailStr] = None
age: Optional[int] = Field(default = None, gt = 0, lt = 100)
@model_validator(mode = 'before')
@classmethod
def check_at_least_one_field(cls, values):
# Reject completely empty payloads — at least one field must be provided
if not any(values.values()):
raise ValueError("At least one field must be provided for update")
return values