I have a REST API with GETs operations which receive a (long) list of parameters (8 parameters, for example). The aim of this operation is to search and filter elements.
Which is the best practice to manage this scenario?:
(1) Receive a list of parameters?:
public ResultType Get(int p1, int p2, string p3...) { ... }
(2) Or receive an object that encapsulate these parameters?:
public class MyClass
{
public int X { get; set; }
public int Y { get; set; }
public string Z { get; set; }
}
public ResultType Get(MyClass parameter) { ... }
Think in an eCommerce scenario in which you want to search and filter "products" by name, description, category, brand, model, price, etc…
Best Answer
AFAIK, there is no firmly established best practice (sorry). However, one can make some recommendations:
Try to avoid using
POST
(instead ofGET
) if the request is safe (i.e. side-effect free, in particular not modifying data). If the parameters are very large, you may have to usePOST
to get around length limitations, but usually this is not a problem (most software supports quite long URLs), and safe requests should useGET
to allow optimizations such as caching and prefetching.If you use
GET
, you must send your parameters as URL parameters1). In that situation, the natural and common solution is to use a list of parameters, so that's what I'd recommend. Yes, the list will be long, but the REST API is (probably) intended for programmatic use, so I don't see a problem with this. Users of the API are free to encapsulate the parameters in an object inside their own code.Technically, you could also put an object into an URL parameter (as JSON, XML or whatever), but that is unusual, so I would avoid it if possible.
1) Strictly speaking, you can use a body with a
GET
request, but this is unusual and generally not recommended; see e.g. HTTP GET with request body.Finally, just as with methods in source code that have long parameter lists, you might want to consider whether the REST API needs a refactoring. Just like in source code, such a long parameter list indicates the API endpoint is doing many different things. Does it make maybe make sense to split it up, or provide default settings? But that's a different question...