I had a little fight with Marshmallow and the ordered=True in class Meta. When ordered=True is set the fields should be outputed in the order specified in the property fields of the class Meta.
Example:
class AuthorSchema(ma.Schema): id = base_fields.Int(dump_only=True) absolute_url = ma.AbsoluteURLFor('api.author', id='<id>') links = ma.Hyperlinks({ 'self': ma.URLFor('api.author', id='<id>'), 'collection': ma.URLFor('api.authors') }) @post_dump(pass_many=True) def wrap(self, data, many): key = 'authors' if many else 'author' return { key: data } class Meta: fields = ( 'id', 'name', 'links', 'absolute_url', ) ordered = True
This was the output.
{
"author": {
"absolute_url": "http://localhost:8080/api/v4/authors/123",
"id": 123,
"links": {
"collection": "/api/v4/authors/",
"self": "/api/v4/authors/123"
},
"name": "Fred Douglass"
}
}
After some Googeling I found out that the culprit was Flask.jsonify. It orders output alphabetically by default. The following setting switches this off.
app.config['JSON_SORT_KEYS'] = False
After this the output was in the specified order.
{
"author": {
"id": 123,
"name": "Fred Douglass",
"links": {
"self": "/api/v4/authors/123",
"collection": "/api/v4/authors/"
},
"absolute_url": "http://localhost:8080/api/v4/authors/123"
}
}
Hope this saves someone else time.