13

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.

Dherik
  • 15,440
  • 11
  • 108
  • 148
angro
  • 151
  • 1
  • 6

4 Answers4

5

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}/
Dherik
  • 15,440
  • 11
  • 108
  • 148
  • 1
    Great approach. – deFreitas Feb 18 '18 at 20:13
  • What about if your entity has as composite id another entity id. Express the whole hierarchy? We are putting trivia just to follow the hierarchy suggestion as we actually just need topicId and questionId to retrieve a question trivia/topic/topicId/question/questionId – user33276346 Jan 05 '21 at 02:07
3

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}
Alexandru Marculescu
  • 5,380
  • 6
  • 33
  • 49
2

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}

Community
  • 1
  • 1
Nkosi
  • 215,613
  • 32
  • 363
  • 426
1

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.

lokesh
  • 463
  • 4
  • 8