RESTful URI – Handling Many-to-Many Relationships

database-designrestweb services

I am having confusion while choosing a database relation and Restful URI for application I am developing.

I am making a simple library application with following requirements.

  1. Book can belong to many categories e.g Physics book belong to Textbook and Science Category. We can say book have many categories/labels/tags.
  2. Viewing books in one category.
  3. Viewing a book's all categories.
  4. Searching book using categories or book information.
  5. Book CRUD operations
  6. Label CRUD operations

Considering all these requirements I choose ManyToMany relation between Books and Labels. I have implemented it using Hibernate Framework.
Now when it came to designing Restful Services for this its getting very confusing.It makes me question table relationship choice as well.

Restful uri made yet.

/books

/books/{bookid}

/labels

/labels/{labelid}

But when I want to get a list of labels against a book, or a list of books against a label. How to map them using Restful URI. I can think of this

/book/{bookid}/labels

But considering this,how to map getting a list of books against one label

I want to know whether my choice of table relationship is right and if yes, how to design restful uri against it. And if no, please correct me and put a light on this scenario. Thanks

Best Answer

Regarding the table, if a book can have many labels and a label many books (sounds quite reasonable) then that's a many to many relationship.

In case of REST the many to many relation is in fact a bit confusing since we talk about resources and with the URI being a unique identifier it seems weird to be able to access one and the same resource from two directions.

Maybe the best way is to see a resource not only as a simple thing (book, label) but also as a specific set of things (books, labels of a book). You often have nested resources anyway and the many to many is just one variant where two different ways to view these sets make sense (assuming that your users will want to access in both variants which seems likely for your use case).

So in fact you would have two ways to access this:

/book/{book_id}/labels

and

/label/{label_id}/books

You will most likely have similar approaches for other resources like authors (author can have written many books and often enough many authors work together on a single book) or even publishers. Categories too I would assume to be many to many.

When sombody selects a single label from above URIs (/book/{book_id}/labels) you can of course then fall back to your normal label URI (/label/label_id) instead of constructing extra long paths like (/book/{book_id}/label/{label_id}).

So keep your routes as shallow as possible, avoid to nest them too deep. But nothing prohibits to have different views on lists of similar things.

Related Topic