Stuart Hemming
Stuart Hemming

Reputation: 1663

Using a POST method in WebApi rather than a GET method. Should I?

I have a REST API that provides access to a resource using GET.

Using this method I can get a specific instance or all instances.

In this case one instance isn't enough and all is too many.

What I've done is create a new Controller with a pattern like /api/filteredresource and made that a POST request with the body containing a representation of a filter to be used to limit the list of items returned.

I'm not looking for a "How do I..." answer, more a "Should I do it this way..." one.

What's the besrt practice here?

This StackOverflow article seems to suggest I shouldn't do it this way as the data canno (or rather should not) be cached but in this instance caching this filtered data doesn't make sense. I suppose I'm looking for a pragmatic answer rather than a technically correct one.

** EDIT ** The inital requirement was to just search for instances of the resource matching a particular status, but it seems that this was to be a 'first step'. They have a 'search key' that they want to use that contains all sorts of properies matching, in many cases, elements of the resource itself and they want to be able to use this 'search key' (or a representation of it) as the filter. ** END EDIT **

Upvotes: 0

Views: 316

Answers (2)

Pedro Werneck
Pedro Werneck

Reputation: 41878

It's fine to use POST for any operation that isn't standardized, but retrieval of any kind is standardized and should be done with GET. As you figured, this depends on how pragmatic you want to be, and how much you want to stick to the standards.

If your problem is that the query string isn't readable or easy to represent, and you really want to stick to REST principles, you should have a query or filter resource subordinated to the filteredresource you want to filter, then it's semantically correct to make a POST with a body of filter parameters. This POST should return a 303 with a Location URI for a GET to the filteredresource, with a querystring that will yield the result you expect. Since this is generated by the API, and doesn't have to be readable, how easy it is to build or read shouldn't be an issue at this point. That URI will be cacheable and you'll be doing your retrieval with GET.

A compromise between pragmatism and purism is having that POST simply returning the result.

If you want to be pragmatic, just POST to `fiteredresource' and don't worry about it.

Upvotes: 1

user1907906
user1907906

Reputation:

Use query parameters to filter:

GET /rest/things/1

gets the thing with id=1.

GET /rest/things

gets all things.

GET /rest/things?color=yellow

gets only the yellow things.

Upvotes: 1

Related Questions