I am trying to figure out if it is possible to pass a JSON object to rest API, Or pass a multiple parameters to that API ? And how to read these parameters in Spring ? Lets assume that the url looks like the below examples :
Ex.1 http://localhost:8080/api/v1/mno/objectKey?id=1&name=saif
Is it valid to pass a JSON object like in the url below ?
Ex.2 http://localhost:8080/api/v1/mno/objectKey/{"id":1, "name":"Saif"}
Questions:
1) Is it possible to pass a JSON object to the url like in Ex.2?
2) How can we pass and parse the parameters in Ex.1?
I tried to write some methods to achieve my goal, but could not find the right solution?
I tried to pass JSON object as @RequestParam
http://localhost:8080/api/v1/mno/objectKey?id=1
There was an unexpected error (type=Unsupported Media Type, status=415). Content type 'null' not supported
http://localhost:8080/api/v1/mno/objectKey/id=1
There was an unexpected error (type=Not Found, status=404). No message available
http://localhost:8080/api/v1/mno/objectKey/%7B%22id%22:1%7D
There was an unexpected error (type=Not Found, status=404). No message available
@RequestMapping(value="mno/{objectKey}",
method = RequestMethod.GET,
consumes="application/json")
public List<Book> getBook4(@RequestParam ObjectKey objectKey) {
...
}
I tried to pass the JSON object as @PathVariable
@RequestMapping(value="ghi/{objectKey}",method = RequestMethod.GET)
public List<Book> getBook2(@PathVariable ObjectKey objectKey) {
...
}
I created this object to hold the id parameter and other parameters like name , etc ....
class ObjectKey{
long id;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}
Multiple parameters can be given like below,
Yes its possible to pass JSON object in URL
No, because
http://localhost:8080/api/v1/mno/objectKey/{"id":1, "name":"Saif"}
is not a valid URL.If you want to do it the RESTful way, use
http://localhost:8080/api/v1/mno/objectKey/1/Saif
, and defined your method like this:Just add two request parameters, and give the correct path.
UPDATE (from comment)
Send that as a
POST
with the JSON data in the request body, not in the URL, and specify a content type ofapplication/json
.you can pass multiple params in url like
http://localhost:2000/custom?brand=dell&limit=20&price=20000&sort=asc
and in order to get this query fields , you can use map like