When working on patch
requests with FastAPI, one may encounter the situation where you would want to ignore fields not supplied in a request.
While you could do this with the Optional
type annotation, this means that you have to use None
as a flag that a field is not set, by setting it as the default value.
This may not be suitable though, when None
is an actual valid value for a field.
In this case, you could use a special value for indicating a missing field.
Below is a code snippet where I have implemented this approach.
The type MissingValueBaseClass
is used for creating an object named Missing
, which can be assigned as the default value for potentially missing fields.
These fields have to be annotated using the function MaybeMissing
, which takes in a type t
and returns a Union
with MissingValueBaseClass
.
By inheriting from ModelMayMissFields
, the class UpdateUser
can return a dict
containing only values that are set with the method get_existing_fields
.