fastapi-crudrouter icon indicating copy to clipboard operation
fastapi-crudrouter copied to clipboard

What is the best way to create a read-only/allow_mutation=False field?

Open jidn opened this issue 3 years ago • 5 comments

Similar to the id field, I have a created_on field the database will auto create for me. Now, what is the best way to not allow the field in POST, PUT but have it in GETs?

  1. Require the use of Create and Update Schema. Nothing would need to change, but all that schema creation smells of boilerplate.
  2. Modify the _utils.py schema_factory to allow for additional fields to exclude. However, at that point you might as well add id to that list and make it generic.
  3. Modify the _utils.py schema_factory to look for allow_mutation and exclude it along with id.
for f in schema_cls.__fields__.values()
if f.name != pk_field_name and f.field_info.allow_mutation

Now my field could look something like

# Not in OpenAPI post or put
update_on: datetime.datetime = Field(
    allow_mutation=False, description="Last update from sync system"
)

Is there a better way to remove fields from Create and Update schemas easily?

jidn avatar Oct 05 '21 04:10 jidn

Hi @jidn thanks for bringing this up.

I totally agree with what you suggested. I think removing fields with allow_mutation=false in the schema factory would be a great way of reducing potential boiler plate. 🚀

Is this something you would be interested in PRing?

awtkns avatar Oct 05 '21 05:10 awtkns

Sure. Any tips where to best insert tests?

jidn avatar Oct 05 '21 13:10 jidn

Is there anything else you need for this patch?

jidn avatar Oct 18 '21 21:10 jidn

Hey thanks for the reminder @jidn. I am planning on merging this in the coming days (with the next release).

awtkns avatar Oct 18 '21 23:10 awtkns

Hey @awtkns , Do you know when this is going to be part of a released version ?

jsenecal avatar Feb 25 '22 13:02 jsenecal