Should the REST API return a 4xx response when an invalid request parameter is provided?

Consider a RESTful API that accepts GET requests to enumerate items:

GET /1.0/items/
>> {"items": [{}, {}, ..., {}]} # All items returned

      

Now consider that each element has a color box and I can filter my elements:

GET /1.0/items?color=blue
>> {"items": [{}, {}, ..., {}]} # Only blue items returned

      

If my API receives an invalid request parameter (not an invalid value for a valid request parameter):

GET /1.0/items?notvalid=blue

      

What should be the expected behavior? Should my API return a response 4xx

informing the client that the request was invalid, or should the API execute the list of items as if no filter parameter had been given?

+3


source to share


2 answers


Should my API return a 4xx response informing the client that the request was invalid, or should the API execute the list of items as if no filter parameter had been given?

/1.0/items?notvalid=blue

identifies the resource. This identifier can be interpreted as a hierarchical part and a request (see RFC 3986 Section 3 ), but the identifier is everything. The document store, when faced with a URI for a resource that does not exist, will respond with a 404 error. Thus, the behavior is perfectly acceptable (the more general error 400 could also be used, but this is not the case).

An alternative approach that deserves attention is to use ignore politics. By treating the URI as a key-value pair expression, expressed as x-www-form-urlencoded, one can liberally accept the request by ignoring keys that are not recognized and providing default values ​​for any missing keys.

Taking this approach, this ID will be treated as if it had been written. /1.0/items?

This gives you some protection against changes (clients and servers do not need to be matched exactly to make progress).



Note: in REST, the client will typically consume hypermedia views that route it over the protocol; that way, the client would discover through the forms or uri templates which parameters were expected as part of the query string. This is indeed the same as ignoring semantics, but applies elsewhere.

should the API execute the list of items as if no filter parameter had been given?

You can explicitly specify the returned link so that the client can detect the discrepancy; for example by redirecting the request to the ID you are about to return, or by returning a Content-Location header .

+2


source


According to the JSON API documentation :

In most cases, the JSON API requires the server to return an error when it encounters an invalid value for the API request parameter specified by JSON. However, for API-specific request parameters (ie, those not defined by the JSON API), the server MAY choose to ignore the invalid parameter and make the request successful, rather than responding with an error .



This is the behavior I usually see in the API.

+1


source







All Articles