flask-restx icon indicating copy to clipboard operation
flask-restx copied to clipboard

Remove Fields when using @api.expect for model

Open bl4ckst0ne opened this issue 5 years ago • 2 comments

Hey, Suppose we have a model that I would like to marshal in GET request, and receive in POST request. There are fields in the POST request that the user should not send. For instance, an auto generated ID of the model.

model = api.model('Model', {
    'id': fields.String,
    'name': fields.String
})

@api.route('/todo')
class Todo(Resource):
    @api.marshal_with(model)
    def get(self):
        return get_from_db()  # marshaling with an id
   
    @api.expect(model, validate=True)
    def post(self):
        item = api.payload
        assert 'id' not in item, 'should not get from the user!'
        item['id'] = str(uuid4())  # auto generated id
        return push_to_db(item)

Is there some convenient way to do so?

bl4ckst0ne avatar Dec 18 '20 10:12 bl4ckst0ne

I would also like to know how to achieve this.

rgevaert avatar Feb 20 '21 18:02 rgevaert

In that case you can use api.inherit.

payload_model = api.model('PayloadModel', {
    'name': fields.String
})

response_model = api.inherit("ResponseModel", payload_model, {
        'id': fields.String,
}

response_model will have id and name fields

tvinagre avatar May 20 '21 16:05 tvinagre