Search code examples
pythonmongodbeve

Different Projections on Resource and Item Endpoints in Python Eve


I'm fairly new to RESTful API. So please bear with my ignorance.

Suppose I have a MongoDB collection foobars with some documents. The structure is like: [{'_id': 1, 'foo': 1, 'bar': 1}, {'_id': 2, 'foo': 2, 'bar': 2},...]

I want to set up two endpoints:

  • GET /api/foobars, this should return a list of _id, i.e [{'_id': 1}, {'_id': 2}].
  • GET /api/foobars/1, this should return a single document whose '_id'==1, i.e {'_id': 1, 'foo': 1, 'bar': 1}.

I set up a projection in the domain

DOMIAN = {
    'foobars': {
        'schema': {...},
        'datasource': {
            'projection': {'_id': 1}
        }
    }
}

This works as expected on the Resource level. But on Item level it still only returns the projected fields.

How should I define the projection properly? Should I set multiple endpoints for the same resource? Thanks!


Solution

  • I came up with a workaround. Perhaps not the RESTful way as it seems redundant.

    DOMAIN = {
        'foobar_list': {
            'schema': {...},
            'datasource': {'source': 'foobars'},
            'projection': {'_id': 1}
        },
        'foobar_item': {
            'schema': {...},
            'datasource': {'source': 'foobars'},
    
            # Disable resource level endpoint
            'resource_methods': [],
        },
    }