flask-restx
flask-restx copied to clipboard
Remove Fields when using @api.expect for model
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?
I would also like to know how to achieve this.
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