amethyst stan
amethyst stan

Reputation: 35

I am using Postman, to pass the data to a REST api but my variable is showing null value

My main question is how to pass a (Map, String) to a REST API, I know if I use @RequestBody all the passed contents are stored to map but what can be done to pass map as well as any other parameters REST API.

@GetMapping(path="/invoices")
public String invoiceReceived( Map<String,Object> invoice,String format) throws MessagingException {
        System.out.println(format); // this prints NULL
        return "returnValue";
}

So I tried using PathVariable but they throw exception. What can be done?

@GetMapping(path="/invoices/{invoiceData}/{format}")
public String invoiceReceived(@PathVariable("invoiceData") Map<String,Object> invoice, 
@PathVariable("format") String format) throws MessagingException {
        System.out.println(format); // this prints NULL
        return "returnValue";
}

What should I do to accept a map and a variable as input? And what should be the JSON file look like which should be given as input?

   {
        "invoiceData":[{"invoiceId":"23642",
        "clientName":"Client",
        "amount":"23742.67",
        "email":"[email protected]"
        }],
        "format":"html"
    }

This question was identified similar to another question, So I am trying to explain how is this different, I know that I can use @RequestBody to get all the variables in the map, but The call will be made with two parameters some of which will be stored in map but one parameter will be used for another variable. So how can I send a map along with any other variable?

Upvotes: 0

Views: 2545

Answers (1)

Tomoki Sato
Tomoki Sato

Reputation: 638

I think you can use query strings and path variables.
If you declare a controller's method like:

@GetMapping(path="/invoices")
public String invoiceReceived(@RequestBody Map<String,Object> invoice, @RequestParam String format)  {
  ...
}

the url to which the request is send and the JSON request body will be something like below.

The url:

http://localhost:8080/invoices?format=html

The JSON request body:

{
  "invoiceId":"23642",
  "clientName":"Client",
  "amount":"23742.67",
  "email":"[email protected]"
}


Also you can use a path variable like:

http://localhost:8080/invoices/html
@GetMapping(path="/invoices/{format}“)
public String invoiceReceived(@RequestBody Map<String,Object> invoice, @PathVariable String format)  {
  ...
}

Upvotes: 1

Related Questions