Passing multiple parameters to Rest API with multiple conditions

Viewed 4172

I am looking at designing a Rest search API which can accept multiple parameters as filters.

For example:

https://test/api/GetCustomer?Filter=”FirstName=test||LastName=test||telephone=043232323”

The above example will basically do a Or between the fields provided. It is passing the whole search string as one parameter. I want to be able to handle a more complex query as well as below:

https://test/api/GetCustomer?Filter=”(FirstName=test||LastName=test)&&telephone=043232323”

I am not too sure what is the best way to implement the endpoint, it would be easier from frond-end perspective to pass it as a single parameter and than do the parsing at the API level. But obviously it will require more effort to be able to parse the query specially if it is a bit more complex.

Is there a better way to implement the scenario?

2 Answers

Ease of use is one of top concerns when building a backend. Ease of implementation comes a distant second. Generally, it is much easier to compose a complex query than to parse it, so front-end developers would be able to build very powerful filtering code with a relatively small effort; this is a good thing.

Although doing the parsing right is somewhat complex, there are parsing tools for managing the complexity, such as ANTLR. Although the learning curve for the new tool may be a little steep, in the end you would get a robust parsing library that makes it easy for front-end developers to consume your service.

var queryString = this.Request.GetQueryNameValuePairs();

List<KeyValuePair<string, object>> QueryStringKeys = new 
List<KeyValuePair<string, object>>();

foreach (var pair in queryString)
{
    QueryStringKeys.Add(new KeyValuePair<string, object>(pair.Key.ToString(), pair.Value));
}

Boolean firstvalue = true;
foreach (var keys in QueryStringKeys)
{
    //access key.Key and key.Value here to make dynamic query
}

This may not be the best way of doing it, but you can pass your results as normal query string variables

https://test/api/GetCustomer?FirstName=test&LastName=test&telephone=043232323
Related