Pipe
Pipe

Reputation: 2424

How to manage GET Method in an API

I'm developing an API, reviewing documentation about HTTP Methods it says that "GET" should not modify the state of the resource. What if I want to count how many times a resource is viewed and return it on the response?

Something like

GET /resource/1
{
   "content": "This is the resource 1",
   "view_count": 1
}

In the next call it returns:

GET /resource/1
{
   "content": "This is the resource 1",
   "view_count": 2
}

Do am I violating some rule?

Upvotes: 4

Views: 76

Answers (2)

Viktor A
Viktor A

Reputation: 146

I would argue that the fact that view_count gets updated while using GET is not much of a violation here if you say that view_count is not a part of the resource itself. It is just some additional data. You could even modify your request to reflect that. Something like GET /resource/1?include=view_count. I think it's called resource expansion by some.

Upvotes: 2

Matthew Cullum
Matthew Cullum

Reputation: 189

Although it's a good practice not to modify the state of a resource with a GET request, I think your use case serves as an exception. I really can't think of another way this could even be accomplished.

Edit:

Someone stated (before deleting their comment) that API users should use a PATCH request prior to every GET request to keep the view_count up to date.

The problem I see with this approach is that the view_count would become unreliable, as you're relying on your API users to keep it up to date.

Imagine if web users had to submit a request to Google Analytics everytime they visited a web page...

Upvotes: 0

Related Questions