Search code examples
eve

How to disallow "_id" in the request while creating resources using Python eve?


I am using Python Eve to implement REST APIs.

While creating a resource with POST, It seems that I can pass a value for "_id" field in the request body and as long as the value fits Mongo's ObjectId format, Eve is using the passed in value as the ID of the resource.

Is there any way to disable this behavior? Basically, I want IDs to be generated by the backend and don't want to allow clients to set them. I checked all the available configuration options and didn't find any in this regard.

Thanks in advance, Raghu


Solution

  • Don't know how to disable, but you can avoid by having a pre_post hook checking for the field in the post body, and abort if found. Something like this:

    from flask import abort
    
    def on_post_check__id(resource, request):
        # handling bulk inserts
        body = request.json if type(request.json) == list else [request.json]
        for item in body:
            if '_id' in item:
                abort(422, '_id not allowed in body.')
    
    app = Eve()
    
    app.on_pre_POST += on_post_check__id
    app.run()