Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REST Best Practise : Return Count with List API

Tags:

rest

We have a REST Service endpoint

OUR_DOMAIN/api/v2/users

This endpoint returns list of active users in our application. Now we need to show total user count as well. For this we thought about two approaches

  1. Add another field in response for count in same listing service end point

{ count : 15, users :[{...},{...}] }

  1. Develop a separate service to return count only

OUR_DOMAIN/api/v2/users : for user listing

OUR_DOMAIN/api/v2/userscount : for user count

I personally prefer option 1 but option 2 seems logical too as according to REST best practises, one REST End Point should serve one specific purpose only. Please suggest according to REST best practises which option is better and why?

Thanks

like image 588
user294754 Avatar asked Apr 26 '26 15:04

user294754


1 Answers

In fact, there are two approach to do that:

  • In the payload. This corresponds to your first option. It implies a different structure for the returned data than the flat one but it's really acceptable

  • In the headers. You can add an header like X-total-count for this. There is also the Link header that is linked if you want to implement pagination. See the Github API for a sample: https://developer.github.com/v3/#pagination.

A separate service returning the number of elements isn't really RESTful since you use a specific verb in the resource path...

Hope it helps you, Thierry

like image 58
Thierry Templier Avatar answered Apr 30 '26 15:04

Thierry Templier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!