Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REST API - Best practice to access embedded resources

We use MongoDB and we provide restful api to access resources (not only collections). For example I have a devices collection. Every device document has an embedded array: carriers. These are association classes for carriers, without any unique id.

{
   _id: ObjectId("..."),
   carriers: [
     {
         carrier: ObjectId("..."),
         bindingInterval: {
           from: ISODate("..."),
           to: ISODate("...")
         }
     },
     ...
   ]
}

In our service the uniqueness of carrier-binding determined by a compound of specific fields: carrier + from + to values.

Question: What is the best restful practice to require these embedded documents? In many cases I GET / POST / PUT / DELETE them individually.

Otherwise it's just an example. We have embedded documents in many other cases.

Ideas:

  1. I describe separately the compound parameters in the query below the main resource's id.
  2. I define a virtual id for embedded documents using a mixin of these parameters and I generalize this approach for similar cases.
like image 810
hasyee Avatar asked Nov 10 '22 03:11

hasyee


1 Answers

As far as I understood you need to access the elements that are not assigned with any ID in a RESTful way.

First of all I'd add a separate endpoint for the carriers only. It will be:

/devices/{deviceID}/carriers/

I don't know why not assign an unique ID on mongo DB level (this seems to be the easiest option) but if it's not possible it's better to refer a given resource via an artificial compound key passed in path rather than sending the parameters separately via query string. So each time you return the collection of carriers assign each element a:

carrierID = md5(carrier+from+to)

With such a key you can easily refer every embedded resource via:

/devices/{deviceID}/carriers/{carrierID}/

It seems that it will be much easier to refer such resources via different endpoints.

The downside is that you need to recalculate the carrierID for all resources on the backend side to check if any of them matches the received one.

I see that you've an ObjectId for each carrier field. Isn't it unique? Why don't you use it?

like image 194
Opal Avatar answered Nov 15 '22 07:11

Opal