Flask Restful: How To Document Response Body With Fields.dict()?
In flask-restplus, I want to model the response body which has nested list strucure, so whenever make api call, response body will be returned what I expected. In responce body, it
Solution 1:
Use @ns.marshal_with(payload).
The decorator marshal_with() is what actually takes your data object and applies the field filtering. The marshalling can work on single objects, dicts, or lists of objects. Marshalling Resource Link: https://flaskrestplus.readthedocs.io/en/stable/marshalling.html
And to model used_features use fields.Nested. I have shown how to use it in the following code.
from flask import Flask, jsonify
from flask_restplus import Namespace, Resource, fields, reqparse
from flask_restplus import Api
app = Flask(__name__)
api = Api(app)
ns = api.namespace('ns')
used_features = {}
used_features['name'] = fields.String(attribute='name')
used_features['value'] = fields.Integer(attribute='value')
used_features['range_value'] = fields.List(
fields.Integer, attribute='range_value')
used_features['range_frequency'] = fields.List(
fields.Integer, attribute='range_frequency')
used_features['importance'] = fields.Integer(attribute='importance')
used_features_payload = api.model('feature_payload', used_features)
payload = api.model('Payload', {
'score': fields.Integer,
'category': fields.String,
'guidance': fields.String,
'is_ready': fields.Boolean,
'used_features': fields.Nested(used_features_payload)
# how to add used features arrays
})
@ns.route('/')classAResource(Resource):
@ns.expect(payload) @ns.marshal_with(payload)defget(self):
parser = reqparse.RequestParser()
parser.add_argument('score', type=str, required=True)
parser.add_argument('category', type=str, required=True)
parser.add_argument('guidance', type=str, required=True)
parser.add_argument('category', type=str, required=True)
parser.add_argument('is_ready', type=bool, required=True)
try: # Will raise an error if date can't be parsed.
args = parser.parse_args() # type "dict"return jsonify(args)
except:
returnNone, 400if __name__ == '__main__':
app.run(debug=True, port=1234)
Post a Comment for "Flask Restful: How To Document Response Body With Fields.dict()?"