Search code examples
pythoneve

Python-Eve: More than one additional lookup


Using additional lookups I am able to access a given document of a desired endpoint by a secondary one as stated in the docs:

Besides the standard item endpoint which defaults to /<resource>/<ID_FIELD_value>, you can optionally define a secondary, read-only, endpoint like /<resource>/<person_name>. You do so by defining a dictionary comprised of two items field and url. The former is the name of the field used for the lookup. If the field type (as defined in the resource schema) is a string, then you put a URL rule in url. If it is an integer, then you just omit url, as it is automatically handled. See the code snippet below for an usage example of this feature.

So recalling the given example from the docs:

people = {
    # 'title' tag used in item links. Defaults to the resource title minus
    # the final, plural 's' (works fine in most cases but not for 'people')
    'item_title': 'person',

    # by default, the standard item entry point is defined as
    # '/people/<ObjectId>/'. We leave it untouched, and we also enable an
    # additional read-only entry point. This way consumers can also perform
    # GET requests at '/people/<lastname>'.
    'additional_lookup': {
        'url': 'regex("[\w]+")',
        'field': 'lastname'
    },

    # We choose to override global cache-control directives for this resource.
    'cache_control': 'max-age=10,must-revalidate',
    'cache_expires': 10,

    # we only allow GET and POST at this resource endpoint.
    'resource_methods': ['GET', 'POST'],
}

Since lastname is set as a secondary endpoint I would be able to access the people endpoint either through the document id (which is default) or the lastname key of a stored document.

Assuming that each person has a unique lastname and a unique nickname. Is there a possibility to define more than one additional lookup in order to have access via the lastname and the nickname?

However, this example is just to show what I am looking for. In my real use case I have a database containing different product information and I want to be able to access those information by both the English and the German title so I can guarantee that all my additional lookups will result in unique document keys.


Solution

  • You can't add more than one additional lookup to the same endpoint. What you can do however, is have multiple endpoints consuming the same datasource.

    Multiple API endpoints can target the same database collection. For example you can set both /admins and /users to read and write from the same people collection on the database.

    Quote is from the Advanced Datasource Patterns. So you could simply have /books/english/<title> and /books/german/<title>. Both endpoints would still consume the same database collection.

    Depending on your schema design you might also go the Sub Resources path and set up something like /products/<language>/books/<title>.