Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REST API URI for resource with multiple primary keys

I am developing a generic REST API for my projects and I'm wondering what to do when I have a table/resource with 2 or more primary keys.

For example, lets suppose I have a table named "question" with two primary keys (date and type) and I need to create the resource REST URI. What is the best way to do it following the standard schema api/{resource}/{id}?

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

Thank you.

like image 799
angro Avatar asked Jun 04 '16 09:06

angro


4 Answers

I think that what you call multiple primarey keys is a composite key. Right?

Maybe, the best alternative for you is:

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

This is more natural to read as a http resource for your case, even if don't make sense have a api/question/date/{:date} in your application.

Another alternative is:

api/questions/{:date}/{type}/
like image 159
Dherik Avatar answered Oct 19 '22 20:10

Dherik


You're on the right path, I think you definitely should include both the date and the type in the resource url if that's the only way you can uniquely identify it

api/question/{date}_{type}
like image 24
Alexandru Marculescu Avatar answered Oct 19 '22 19:10

Alexandru Marculescu


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

with that, you have a few options at your disposal. Which is the best would be a matter of opinion and what suits your needs.

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

The same pattern could also be applied to the following.

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

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

like image 2
Nkosi Avatar answered Oct 19 '22 19:10

Nkosi


I do not find it a good idea of having two primary keys for a resource. REST heavily depends on resources and it's representations.

If you are struck into situation where you are ending up with two identifiers for a resource - then redesign your application (may be by creating another key in backend after mapping it to other identifiers) and add these multiple keys as attributes in resource.

Idea is - "keep it simple" if you want to create truly world class REST APIs.

Bonus: You don't need to teach few extra things to clients/developers about something fancy you did with your APIs.

like image 1
lokesh Avatar answered Oct 19 '22 19:10

lokesh