NibblyPig
NibblyPig

Reputation: 52932

Passing complex parameters into a GET request

I have a [HttpGet] web api method called GetCats() that returns a collection of Cat objects.

I added parameters skip and take to allow pagination.

However the requirements have increased and now there must be the possibility of complex filtering, in the case of a collection of filters in the format "PropertyName", "Value", "Type" eg. "CatName", "Mittens", "EqualTo" and Sort filters in the format "PropertyName", "Direction" e.g. "CatAge", "Descending".

Skip and Take is also required.

When this filter object is built up it can be quite large and complex. As a result it doesn't seem to be feasible to put it into the QueryString anymore especially if there are multiple filters as you'd need a way to group them together.

I am looking for a solution - I think I could use [HttpPost] and just post the filter but it seems wrong for a HTTP method. I'm not sure if I can somehow encode the object into the querystring and gracefully decode it or not.

Could anyone suggest a fix for this? I suspect it must be a common problem to pass complex parameters into a GET to retrieve a collection of data.

Upvotes: 3

Views: 4377

Answers (2)

Tim Norris
Tim Norris

Reputation: 266

The way to do this for GET requests is the querystring.

As you already mentioned, for POST requests the data can be passed in the body.

An unorthodox method would be to use the HTTP headers and send some info that way, but this may not sit well with some purists!! And it also might get fiddled with by some networks.

It's up to you to find the balance between what works and what's acceptable in your design.

Upvotes: 1

Alexei Levenkov
Alexei Levenkov

Reputation: 100527

I think you can stick with regular query parameter for most practical query cases.

Default query string limit is 2048 in IIS. This is pretty long for 40-100 individual query string parameters by default, more if you keep names short. You can also increase it as needed - IIS Request Limits.

If parameters are complex enough you can convert it to JSON and as as single query parameter.

Unless you have either ideological objection (like "must be REST interface") or technical reasons (like you need caching and your CDN does not allow caching of POST requests) there is nothing wrong with posting your parameters. Or if you want to stick with GET you can put more parameters in headers (but that feels very hacky and does not buy you much).

Upvotes: 3

Related Questions