We are doing an attribute search on Products, and creating a search API.
The Products API, has attributes in its Request including VendorId (who sell the product), and LocationId (of where its sold). Below, is it best to make Vendor and LocationId an Array , instead of single? The front end search only allows single select dropdown. However what is best API practice of back end, to make it multiid search, in case of future requirements? I don't want to couple back end with front end.
public class GetProductRequest {
private String productSearchString;
private Integer locationId;
private Integer providerId;
private String sortField = "ProductName,desc";
private int pageNumber = 0;
private int pageSize = 10;
}
SQL Query:
select distinct product.*
from dbo.productContract
left join dbo.product
on productContract.productId = product.productId
left join dbo.vendor
on productContract.vendorId = vendor.vendorid
left join dbo.location
on productContract.locationId = location.locationId
where productContract.vendorId in (@vendorIds) and productContract.LocationId in (@LocationIds)
The only change in back end is converting where ==
to where in
for multiple.
CodePudding user response:
It depends.
The REST api is about the resource therefore it would be a nonsense to have an endpoint like
.../api/v1/product
that is accepting more than one applicable search criteria field value because it would return what - an array? First valid?
Just think how weird it would be also for the user to send one-element array because the API requires it.
Another story when you have
.../api/v1/products
Then multiple search criteria is totally fine and expected.
In my opinion you should provide two endpoints and for every of them you should have another request payload - in case of singular resource the search criteria fields should be definitely single, for the list of resources - well, in my opinion you could rather accept the list of requests that will describe valid products.
[
{
productName:"sneakers",
locationId:"US",
providerId:"Nike",
...
},
// ... OR
{
productName:"sneakers",
locationId:"US",
providerId:"Adidas",
...
},
...
]
Also, please remember about YAGNI rule. Do not implement the total, ultimate, "I'm never gonna take a look at this again" backend REST API :)