I'm trying out JsonPatch but ran into an issue when I try to test it. My REST controller looks like this:
#RestController
#RequestMapping("/v1/arbetsorder")
class ArbetsorderController {
#PatchMapping(path ="/tider/{tid-id}", consumes = "application/json-patch+json")
public ResponseEntity<Persontid> patchTid(#PathVariable("tid-id") Long id, #RequestBody JsonPatch patch) {
Persontid modifieradPersontid = personTidService.patchPersontid(id, patch);
return new ResponseEntity<>(modifieradPersontid, HttpStatus.OK);
}
}
I'm testing this endpoint using this method:
#Test
void patchPersontid() {
String body = "{\"op\":\"replace\",\"path\":\"/resursID\",\"value\":\"Jonas\"}";
given()
.auth().basic(user, pwd)
.port(port)
.header(CONTENT_TYPE, "application/json-patch+json")
.body(body)
.when()
.patch("/v1/arbetsorder/tider/3")
.then()
.assertThat()
.statusCode(HttpStatus.OK.value())
.body("resursID", equalTo("Jonas"));
}
But this test fails because the status code is 500 instead of 200. I'm not reaching my endpoint.
I have tried using regular JSON and then everything works fine.
Can anyone help me understand why I'm not reaching my endpoint when using JsonPatch?
Apparently the body I send to the endpoint has to be an array in order for it to be converted to a JsonPatch object. Changing my body to:
String body = "[{\"op\":\"replace\",\"path\":\"/resursID\",\"value\":\"Jonas\"}]";
solved my problem!
Related
I have a service call that returns Mono. Now while giving API response to user I want to send some response. I tried with flatMap as well as a map but it won't work. It gives me an empty body in response.
Here the code sample
//Service Call
public Mono<Void> updateUser(....) {
.......... return Mono<Void>...
}
//Rest Controller
#PostMapping(value = "/user/{id})
public Mono<Response> update(......) {
return service.updateUser(....)
.map(r -> new Response(200, "User updated successfully"));
}
When I hit the above API it gives me an empty body in response. Can anyone please help me to get body in API response?
Thank you
if you wish to ignore the return value from a Mono or Flux and just trigger something next in the chain you can use either the then operator, or the thenReturn operator.
The difference is that then takes a Mono while thenReturn takes a concrete value (witch will get wrapped in a Mono.
#PostMapping(value = "/user/{id})
public Mono<Response> update(......) {
return service.updateUser(....)
.thenReturn(new Response(200, "User updated successfully"));
}
I have a REST controller that defines an interface which takes an optional request body.
#RestController
#RequestMapping(ExampleRest.EXAMPLE_URI)
public class ExampleRest {
public static final String EXAMPLE_URI = "/examples";
#RequestMapping(value = "/search", method = POST)
public Page<ExampleDto> search(#RequestBody(required = false) Searchable searchable, Pageable pageable) {
return exampleService.findAll(searchable, pageable);
}
}
The Searchable object contains information to create a JPASpecification. It's pretty much a dto. I would like to make this searchable optional. I understood that #RequestBody(required = false) should do the trick.
I have the following test, where I want to test a request without any request body.
#Test
public void post_NoCriteria_Ok() {
RequestEntity requestEntity = new RequestEntity(HttpMethod.POST, URI.create(ExampleRest.EXAMPLE_URI + "/search"));
ResponseEntity <RestResponsePage<ExampleDto>> response = restTemplate.exchange(requestEntity, new ParameterizedTypeReference <RestResponsePage<ExampleDto>> () {});
Assert.assertEquals(HttpStatus.OK, response.getStatusCode());
}
If I run this test, it keeps failing with this response from the RestController:
<415 Unsupported Media Type,Page 1 of 1 containing UNKNOWN
instances,{Content-Type=[application/json;charset=UTF-8],
Transfer-Encoding=[chunked], Date=[Wed, 13 Sep 2017 10:10:22 GMT]}>
The Code execution does not even enter search method implementation inside of the RestController.
As soon I provide an empty Searchable for the test, it runs through.
Is the implementation of #RequestBody(required = false) buggy, or what am I doing wrong here?
You need to set Content-Type as "application/json" in your request while sending from #Test file.
Got a small problem on my rest server. It's based on spring web framework.
Here's the code that poses me problems :
#RestController
#RequestMapping("users")
public class usersWS {
//some other functions
//works
#RequestMapping(
value="/{iduser}/functions/",
method=RequestMethod.GET,
produces={"application/json"})
public ResponseEntity<String> getUserFunctions(#PathVariable("iduser") String iduser){
//do stuff
return stuff;
}
//Don't works
#RequestMapping(
value="/{iduser}/functions/"
method=RequestMethod.PUT,
consumes={"application/json"})
public ResponseEntity<String> addUserFunctions(#RequestBody String json, #PathVariable("iduser") String iduser){
//do stuff
return stuff;
}
}
Server is launched by :
#SpringBootApplication()
#ImportResource("classpath*:**/jdbc-context.xml")
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
To call this server, I use the HTML handler found here : Spring HTTP Client
When I call the get verb, everything is working fine. I get the iduser, get the data I want, no problem.
When I call the put verb... I have an error 404. I checked, the url (http://localhost:8080/users/xxx/functions/) are exactly the same, I do send the body.
I would understand to get a 405 error, but I really don't understand how I can have a 404. If the mapping was wrong, the server should at least see that there is a function on the get verb and throw me a 405.
I have other functions using the PUT/POST that are working but they don't have a #PathVariable. Is it possible to mix #RequestBody and #PathVariable ?
Any help is gladly welcome.
i have a REST api service which should receive POST calls.
I'm using POSTMAN to test them, but i keep getting a 400 Bad Request Error, with no body, maybe i'm building bad my controller...
This is the controller
#PostMapping("/object/delete")
public ResponseEntity<?> deleteObject(#RequestBody long objectId) {
logger.debug("controller hit");
Object o = service.findByObjectId(objectId);
if(o!=null){
service.deleteObject(object);
return new ResponseEntity<>(HttpStatus.OK);
}
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
Using #RequestBody i should send the request in JSON, in this way:
{
"objectId":100
}
But i get a 400 error, and the strange think is that my logger logger.debug("controller hit"); it's not printed in logs...
Sending { "objectId":100 } would result in receiving an object X with an objectId attribute in your java method.
If you just need to send an id, you can use #PathVariable
#PostMapping("/object/{id}/delete")
public ResponseEntity<?> deleteObject(#PathVariable("id") long objectId) {
Also, consider using DeleteMapping instead of PostMapping to delete an object.
i am trying to access gaana api from java side by using mashape api
i am trying from a localhost. but, i am getting issues while trying to connect gaana api.
Below is my code in one of my rest service ( I am using spring-security and java8). I am Btech-CSE final year student.
#RestController
#RequestMapping("/api/ideas")
public class IdeaController {
#RequestMapping(method = RequestMethod.GET)
public void invokeGaanaAPI() throws UnirestException {
System.out.println("hello");
// These code snippets use an open-source library.
// HttpServletResponse<JsonNode> response =
Unirest.get("https://community-gaana.p.mashape.com/index.php?subtype=most_popular&type=song")
.header("X-Mashape-Key", "iWEvla5JyCmshafdpHdjoSdtPsHPp1Ily4qjsnCEiVxbQsY5tn")
.header("Accept", "application/json")
.asJson();
Unirest.get("https://community-gaana.p.mashape.com/user.php?type=registrationtoken")
.header("X-Mashape-Key", "iWEvla5JyCmshafdpHdjoSdtPsHPp1Ily4qjsnCEiVxbQsY5tn")
.header("Accept", "application/json")
.asJson();
System.out.println("hello");
}
}
I need help to proceed in this situation. any kind of help is fine for me. i am getting data as null. so, json conversion is throwing null pointer exception.
I am passionate to do this project.
Your data is null because you haven't assigned the Unirest.get() return value to anything.
Please read the docs on using this API.