0

Using JSON Hyper-Schema via Flask-Potion, I have an API that returns a list of species found at /api/species. It returns something like this:

[
{
    "$uri": "/api/species/1",
    "latin_name": "danio rerio",
    "name": "zebrafish"
}
]

For my web frontend, I'd like /species/1 to be the user facing URL that obtains its data for display purposes from /api/species/1. This user facing URL has nothing to do with the underlying API except it makes sense to map the IDs since how else will I format my user facing URLs? So when I have a list of species that should link to their respective species pages, how to I form /species/1? Since the $uri I get from my API is the API uri, am I supposed to parse this string to extract "1" or is there a more elegant solution that I'm missing here?

lyschoening
  • 18,170
  • 11
  • 44
  • 54
Brandon
  • 668
  • 8
  • 22

1 Answers1

1

There are several approaches to do this in Potion. The choice of "$uri" as object identifier is not specific to JSON HyperSchema, it is simply the default configuration option in Potion.

If you wish to use the "$uri" field, you have to parse it to retrieve the ID. But you can also tell Potion to instead return an "$id" field with a numeric ID using Meta.id_field_class documented here.

class SpeciesResource(ModelResource):
    # ...
   class Meta:
      id_field_class = fields.Integer

You can combine this with a "$type" field by setting Meta.include_type = True

Generally, if you want to add a read-only field of any type to your resource, just specify it in the schema:

class SpeciesResource(ModelResource):
    # ...
    class Schema:
        id = fields.Integer(io='r')
lyschoening
  • 18,170
  • 11
  • 44
  • 54