Home > Enterprise >  How to implement search API using POST request in spring
How to implement search API using POST request in spring

Time:04-28

I have a scenario wherein I am supposed to search an object using POST request(instead of expected "GET") having the search criteria as the body of the request, something similar to the following:

{
      "criteria": {
            "value": "BMC_BaseElement",
            "identifier": "some value"
      }
}

Now let's say I need to search on the basis of "value" and "identifier". Do I need to create a corresponding "criteria" POJO and let spring deserialize it, fetch the "value" and "identifier" using getters and then search or how is it generally done?

CodePudding user response:

You can create a POJO model for the request body or, in this case, you could do something like this:

import com.fasterxml.jackson.databind.node.ObjectNode;

@PostMapping("/search")
public ResponseEntity<List<Object>> search(@RequestBody ObjectNode body) {
    String value = body.at("/criteria/value").textValue();
    String identifier = body.at("/criteria/identifier").textValue();
    return ResponseEntity.ok(List.of());
}
  • Related