Wednesday, September 20, 2017

what is the correct way to create a REST endpoint with relationship

Leave a Comment

I want to create some endpoints to retrieve exceptions per country, startTime and endTime but i don't know what is the correct way to structure the endpoints, i have been talking with my co workers and we have different opinions about how to do it :

Option 1 Path params

  • /countries/{countryCode}/exceptions?startTime={value}&endTime={value} : To get all the exceptions per country in a certain timeframe

  • /countries/*/exceptions?startTime={value}&endTime={value} :To get all the exceptions in a certain timeframe

Option 2 Query params

  • /exceptions?country={countryCode}&startTime={value}&endTime={value} :To get all the exceptions per country in a certain timeframe

  • /exceptions?startTime={value}&endTime={value} :To get all the exceptions in a certain timeframe

Option 3 Path params in a different order

  • /exceptions/countries/{countryCode}?startTime={value}&endTime={value} :To get all the exceptions per country in a certain timeframe

  • /exceptions?startTime={value}&endTime={value}: To get all the exceptions in a certain timeframe

All the 3 options have pros and cons but we don't agree in which is the best practice. The question is what is the best option to create these endpoints.

3 Answers

Answers 1

If the exception needs a country to exist, that is, the exception is a sub resource of country, consider:

/countries/{countryCode}/exceptions?startTime={value}&endTime={value} 

Otherwise go for:

/exceptions?country={countryCode}&startTime={value}&endTime={value} 

Answers 2

Option 2 where Exception is a separate first-level entity and the endpoint accepts an optional country code as a filtering property makes the most sense based on the limited description of your requirements.

Answers 3

Path parameters should be used when you are displaying a hierarchy, e.g. to show all the comments that respond to the blog with id {id}, you would form this endpoint:

/blogs/{id}/comments 

If you would want to filter these comments base on time, you would use query parameters for that:

/blogs/{id}/comments?start={start}&end={end} 

In your case however, it seems, based on your question, that you have a large list with exceptions. This list can be filtered based on various aspects:

  • Country
  • Time

Since these properties are not part of the structural hierarchy (based on the context of your question), but simply properties giving more information about the exceptions, it would make sense to catch all them as query parameters to filter on, as such:

/exceptions?country={countryCode}&startTime={value}&endTime={value} 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment