REST API URI for a resource with multiple primary keys

I am developing a common REST API for my projects, and I wonder what to do when I have a table / resource with 2 or more primary keys .

For example, let's assume that I have a table called “question” with two primary keys (date and type), and I need to create a REST URI resource. What is the best way to do this using the standard api/{resource}/{id} scheme?

Maybe something like: api/question/{:date},{:type} ? What is the best way to do this?

Thanks.

+7
rest restful-architecture api-design
source share
4 answers

You are on the right track, I think you should definitely indicate the date and type of the resource URL, if this is the only way to uniquely identify it

 api/question/{date}_{type} 
+2
source share

This is a good example of when to use slugs. This answer What is slug gives you a good idea of ​​how you can use your composite primary key in your api design.

With this, you have several options at your disposal. What is best is a matter of opinion and what suits you.

  • api / question / {: date} / {: type} or api / question / {: key1} / {: key2} /.../ {: keyn}

The same pattern can be applied to the following.

  • api / question / {: date} _ {type}

  • api / question / {: date} - {type}

+2
source share

I think that what you call a few primarey keys is composite. Correctly?

Perhaps the best alternative for you:

 api/questions/date/{:date}/type/{:type} 

It is more natural to read as an http resource for your case, even if it does not make sense to have api/question/date/{:date} in your application.

Another variant:

 api/questions/{:date}/{type}/ 
+2
source share

I do not consider it a good idea to have two primary keys for the resource. REST is highly dependent on resources and its representations.

If you are in a situation where you are running out of two identifiers for a resource, then redesign your application (maybe by creating another key in the backend after matching it with other identifiers) and add these several keys as attributes in the resource.

The idea is to "keep it simple" if you want to create a truly world-class REST API.

Bonus: You do not need to teach a little extra stuff to clients / developers about something that you did with your APIs.

+1
source share

All Articles