python-restx / flask-restx

Fork of Flask-RESTPlus: Fully featured framework for fast, easy and documented API development with Flask
https://flask-restx.readthedocs.io/en/latest/
Other
2.16k stars 335 forks source link

Remove Fields when using @api.expect for model #265

Open bl4ckst0ne opened 3 years ago

bl4ckst0ne commented 3 years ago

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?

rgevaert commented 3 years ago

I would also like to know how to achieve this.

tvinagre commented 3 years ago

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