FastAPI and Pydantic are great, but in a situation where creating models through inheritence/mixins isn't practical (code generation from database queries, for example), it is difficult to remove keys from input models.
Having not found a good solution, here are two I've come up with.
I really wanted sans_fields
to work, as it was my first solution and can be used dynamicly.
Unfortunately due to typehint Forward Referencing it breaks if non-basic types are used (datetime, date, UUID, 'Foo', etc.).
Calling update_forward_refs
doesn't seem to fix things, neither does having the import in the namespace before running it.
If objects are simple it works.
The second method I've found, that I expect I'll use going forward is a mixin that hides the field from FastAPI and allows makes the field optional.
The downside is that it isn't dynamic.
I think it is useful for foreign keys, indices, or creation date fields that you don't want to receive from the user.
For this I created a mixin that makes the field optional and uses the schema_extra
from Pydantic.
The only other thing worth noting here is that the inheritance order matters, the mixin needs to go before the model.
If anyone finds a better way of doing this I would appreciate the comments.
Removing from schema outputs: Though I think the documentation might have a mistake, I used delete rather than looping and popping.
https://pydantic-docs.helpmanual.io/usage/schema/#schema-customization