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.
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}/
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}
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.
The same pattern could also be applied to the following.
api/question/{:date}_{:type}
api/question/{:date}-{:type}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With