Skip to content

JSON encoding and decoding

Thomas Pollet edited this page Mar 29, 2020 · 5 revisions

to_dict

The "attributes" JSON dictionary produced by the API is created by the to_dict method of SAFRSBase. This method can be overridden to produce a customized response. An example of this is implemented in the demo_pythonanywhere_com.py :

    def to_dict(self):
        result = SAFRSBase.to_dict(self)
        result["custom_field"] = "some customization"
        return result

This method will add a custom field to the JSON result:

{
  "data": {
    "attributes": {
      "custom_field": "some customization", 
      "name": "name0"
    }, 
    "id": 1, 
    "links": {
      "self": "http://127.0.0.1:5000/api/Publishers/1/"
    }, 
    "type": "Publisher"
  }
}

JSON Encoding

Object attributes are encoded from their database type to json by SAFRSJSONEncoder, default JSON encoder. This class can be extended to implement custom encoding. the demo_geoalchemy.py example implements custom json encoding:

class GeoJSONEncoder(SAFRSJSONEncoder):
    """
        json encode geometry shapes
    """
    def default(self, obj, **kwargs):
        if isinstance(obj, _SpatialElement):
            result = geometry.mapping(to_shape(obj))
            return result

        return super().default(obj, **kwargs)

This encoder can be passed as an argument to SAFRSAPI, where it will be used to encode database data produced by the API:

SAFRSAPI(app, json_encoder=GeoJSONEncoder)

JSON decoding