Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rest API Best Practices: Multiple parameters search filter API implementation

I am currently implementing a Rest API for search query. The method takes multiple filter parameters, such as keyword, name, title, description, date, etc. In order to stay DRY and avoid repeated if else clause, I am looking for the best practices way to retrieve the resource from database. Lets say the database exposes two methods, findByUsername(...) and findByDescription(), and we want to expose them through a restful web interface. A naive implementation will be using if and else clause similar to below.

@GET
@Path("users")
public User getUsers(@QueryParam("username") String username, 
    @QueryParam("description") String description) {
    User user = null;
    if (username != null) {
        // execute findByUsername method to the database
        user = findByUsername(username);
    } else if (description != null) {
        // execute findByDescription method to the database
        user = findByDescription(description);
    }
    return user;
}

The question is how to improve the code above in order to avoid redundant if else (checking) clause and keep staying DRY? I am implementing the web services using Jersey JaxRS 2.0

like image 623
Lunayo Avatar asked Oct 21 '22 19:10

Lunayo


1 Answers

I would create one finder method and not two or more.

It would accept an object. MongoDB is quite good at this, I think.

So if you search for {username: "X"}, it will give you what you need. If you search for {description: "Y"}, it will give you what you need. Also, if you search for {username: "X", description: "Y"}, it will give you what you need.

Expose a POST method in your REST, it is more flexible and gives you more. Make it accept XML or JSON. If it accepts JSON, you can even easily pass it down to MongoDB (with some validation checking and all that beforehand).

So I hope you see what I mean. I would create one general method and not two or more methods.

like image 63
peter.petrov Avatar answered Oct 24 '22 01:10

peter.petrov