RESTful API Design – Managing Relationships

apiapi-designrestweb-api

Lets say we are making an API with two resources: Author and Book where books can have many authors and authors can have many books.

So we design the REST api like so:

/books
/books/:id
/books/:id/authors
/authors
/authors/:id
/authors/:id/books

Should, for example, /books/:id return the Book with the given id and the various Authors? Or should it return the Book with the given id and the ids of the various Authors which can then be queried either via a bunch of queries to /authors/:id or /authors?ids=1,2,3, etc.?

Best Answer

If, instead of api endpoints, these were web pages on a web site, how would you arrange them?

If you guessed wrong, or worse yet had to somehow do it more than one way, what would you do?

In most cases, the answer is: you would create more documents, and add extra links to help people reliably find the document that is best for them.

Think about it: how many different Hemingway web pages are there on the internet?

The web is not your domain, it's a document management system. All the HTTP verbs apply to the document management domain. URIs do NOT map onto domain objects - that violates encapsulation. Work (ex: issuing commands to the domain model) is a side effect of managing resources. In other words, the resources are part of the anti-corruption layer. You should expect to have many many more resources in your integration domain than you do business objects in your business domain. -- Jim Webber 2011

Your REST API is an attempt to disguise your domain model as a web site. Let the web be your guide.

Related Topic