Replies: 4 comments
-
This is a good question! My suspicion is that there isn't a solution that works in full generality with full type-safety and uses less code than just creating separate models for each usage pattern. You can get some reuse via inheritance: class Profile(BaseModel):
first_name: str
last_name: str
title: str = None
age: int = None
tagline: str = None
class ProfilePatch(Profile):
first_name: str = None
last_name: str = None This is typically what I do to handle this "problem" in my projects. I don't think it would be too hard to make a patch-model-generating function through the use of |
Beta Was this translation helpful? Give feedback.
-
Funny enough, I had just posted that idea as well in my work slack 😅 It does seem to be a more reasonable approach. |
Beta Was this translation helpful? Give feedback.
-
Yeah, as @dmontagu says, that's the current best approach available, using inheritance. The thing is that you need to somehow declare some specific fields as optional in some cases, and as strictly required in others. And each case doesn't depend on the model itself but on external code (your path operation code / HTTP method used). You could do some advanced magic tricks with |
Beta Was this translation helpful? Give feedback.
-
Assuming the original issue was solved, it will be automatically closed now. But feel free to add more comments or create new issues. |
Beta Was this translation helpful? Give feedback.
-
Description
This is half a question on conceptual ideas, and half a feature request maybe?
I was wondering if anyone here has any thoughts on the following scenario.
Say I'm making a profile API. When posting a new profile, you use this model
First name and last name are understandably required fields, because we have to have something for a profile.
So now I want to add a patch endpoint, where you can just edit a single field. For that we want to enable the following request:
But I haven't given a first and last name, so obviously this endpoint can't use the Profile model as its body model.
What is the best approach for this? I can think of a variety of options, but nothing really
sparks joy.
Obviously one approach is to just make a different model for patch. This is certainly the most straightforward, but across a large service you might end up with a lot of duplicate models. And you'll have to manually maintain similarities between the two 🤢
Another thought I had (not sure how easy this would be with Fast built in behaviors? I might be missing something), was to maybe bring the method
POST v PATCH
into a field on the profile model, and write a validator that is dependent on the value of that method field...but that is definitely a bit hacky 😬There are likely lots of other ideas, just curious what the thoughts are from other users of this API (and or the creator)
Beta Was this translation helpful? Give feedback.
All reactions