3

I am building an API using python-eve.

My design is something simple, it has two resources, users and devices:

  • /users[/ID]
  • /users/ID/devices[/ID]

The code is (settings.py) is:

users_schema = {
  'nickName': {
    'type': 'string',
    'required': True,
  },
  'email': {
    'type': 'string',
    'required': True,
    'unique': True
  }
}

devices_schema = {
  'name': {
    'type': 'string',
    'required': True,
  },
  'user_id': {
    'type': 'objectid',
     'data_relation': {
        'resource': 'users',
        'embeddable': True
    },
  }
 }

users = {
  'item_title': 'user',
  'url': 'users',
  'schema': users_schema,
}

user_devices = {
  'resource_title': 'devices',
  'url': 'users/<regex("[a-f0-9]{24}"):user_id>/devices',
  'schema': devices_schema,
  'datasource': {
    'source': 'devices',
  }
}

DOMAIN = {
 'users': users,
 'user_devices': user_devices 
}

If I create an user, the user resource looks like (/users/54465ae80640fd0f60f6aa09):

{
"_updated": "Tue, 21 Oct 2014 13:08:56 GMT",
"_etag": "d6ff9457f5b196a8c245a7dc91e7fca0d28c5268",
"_links": {
    "self": {
        "href": "/users/54465ae80640fd0f60f6aa09",
        "title": "user"
    },
    "parent": {
        "href": "",
        "title": "home"
    },
    "collection": {
        "href": "/users",
        "title": "users"
    }
},
"_created": "Tue, 21 Oct 2014 13:08:56 GMT",
"_id": "54465ae80640fd0f60f6aa09",
"nickName": "superuser",
"email": "super@user.com"
}

HATEOAS is enabled by default. In the previous resource, I was expecting a link to the user devices, to /users/54465ae80640fd0f60f6aa09/devices, because this endpoint exist, is defined in the code (user_devices), and works fine.

Who can I make pyhon-eve understand the relation between user and user-devices, to add this devices links to the user resource? Otherwise, the user 54465ae80640fd0f60f6aa09 will not know how to get the devices.

I am expecting something like:

{
"_updated": "Tue, 21 Oct 2014 13:08:56 GMT",
"_etag": "d6ff9457f5b196a8c245a7dc91e7fca0d28c5268",
"_links": {
    "self": {
        "href": "/users/54465ae80640fd0f60f6aa09",
        "title": "user"
    },
    "devices": {
        "href": "/users/54465ae80640fd0f60f6aa09/devices",
        "title": "devices"
    },
    "parent": {
        "href": "",
        "title": "home"
    },
    "collection": {
        "href": "/users",
        "title": "users"
    }
},
"_created": "Tue, 21 Oct 2014 13:08:56 GMT",
"_id": "54465ae80640fd0f60f6aa09",
"nickName": "superuser",
"email": "super@user.com"
}

Where is "obvious" how to get the devices.

Thank you very much.

MTG
  • 551
  • 3
  • 14

2 Answers2

1

You must add a link between a user => device too

users_schema = {
      'nickName': {
        'type': 'string',
        'required': True,
      },
    'data_relation': {
        'resource': 'user_devices',  # link to device on a field _id
        'field': '_id',
        'embeddable': True
    },
      'email': {
        'type': 'string',
        'required': True,
        'unique': True
      }
    }
HOT_BBQ
  • 53
  • 7
  • Hi! Thanks! I tried it, but I still do not have any relation to "user_devices" in the "user" _links. Can you provide the full code? Thanks again! – MTG Mar 04 '16 at 19:36
  • data_relation the only think it provides is to render the full object adding `?embedded={"user_devices._id":1}` at the end of the query. The expected HATEOAS behavior is to create a new _link section which I think is not covered by Eve out of the box – Carlos Verdes Feb 11 '19 at 13:44
0

I created a custom hook to link an item with other collections.

Add the next code to your app and then define data_relation between your item and the related collection.

For example I have menus linked by parent_node, so I have two relations on my schema:

  • items which parent_menu is current item --> children
  • parent_menu --> children

So I have next schema (first relation for children second for parent):

"menu": {
  "type": "dict",
  "schema": {
    "_id": {
      "type": "objectid",
      "data_relation": {
        "resource": "menu",
        "field": "parent_menu",
        "embeddable": False,
      }
    },
    "id": { "type": "string" } ,
    "label": { "type": "string" },
    "url": { "type": "string" },
    "parent_menu": {
      "type": "objectid",
      "data_relation": {
        "resource": "menu",
        "field": "_id",
        "embeddable": True,
      },
    },
  },
},

This is how the root menu is rendered (not parent, only children with link_rel "menu":

{
  "_id":"5c6ab8a5467a938b027aae64",
  "id":"root",
  "label":"Home",
  "url":"/",
  "_links":{
    ...
    "self":{
      "title":"Menu",
      "href":"menu/5c6ab8a5467a938b027aae64"
    },
    ...
    "menu":{
      "title":"menu",
      "href":"menu?where={\"parent_menu\":\"5c6ab8a5467a938b027aae64\"}"
    }
  }
}

And this is how the children looks like (parent and children links):

{
  "_id":"5c6ab8a5467a938b027aae65",
  "id":"submenu1",
  "label":"Submenu1",
  "url":"/#submenu1",
  "parent_menu":"5c6ab8a5467a938b027aae64",
  "_links":{
    ...
    "self":{
      "title":"Menu",
      "href":"menu/5c6ab8a5467a938b027aae65"
    },
    ...
    "menu":{
      "title":"menu",
      "href":"menu?where={\"parent_menu\":\"5c6ab8a5467a938b027aae65\"}"
    },
    "parent_menu":{
      "title":"menu",
      "href":"menu/5c6ab8a5467a938b027aae64"
    }
  }
}

Code for the app:

def createLink(ref_collection, ref_field, ref_value):

    print(f"createLink({ref_collection}, {ref_field}, {ref_value})")
    ref_value = f"{ref_value}"
    linkSufix = "/" + ref_value if ref_field == "_id" else "?where={\"" + ref_field + "\":\"" + ref_value + "\"}"

    linkRel = {
        "title": ref_collection,
        "href": ref_collection + linkSufix,
    }
    print(f"createLink result: \n{linkRel}")

    return linkRel

def add_links(resource_name, resource, schema):

    linked_item_keys = list(key for key in schema if "data_relation" in schema[key] and key in resource)
    print(f"linked_item_keys: {linked_item_keys}")

    for key in linked_item_keys:

        print(f"link needed for: {resource_name}.{key}")
        itemSchema = schema[key]
        item = resource[key]

        data_relation = itemSchema["data_relation"]
        ref_collection = data_relation["resource"]
        ref_field = data_relation["field"]

        link = createLink(ref_collection, ref_field, item)

        links = resource["_links"] if "_links" in resource else []
        link_rel = ref_collection if resource_name == ref_collection  and key == "_id" else key
        links[link_rel] = link
        resource["_links"] = links

def add_links_to_item(resource_name, response):
    print(f"------------------------------------")
    print(f"(on_fetched_item) {resource_name} ")
    print(f"response: \n{response}")

    schema = config.DOMAIN[resource_name]["schema"]
    print(f"""schema: \n{schema}""")
    add_links(resource_name, response, schema)

app = Eve()
app.on_fetched_item += add_links_to_item

Hope it helps!!

Carlos Verdes
  • 3,037
  • 22
  • 20