#FeignClient forces #GetMapping with #RequestBody to POST - java

I have following REST controller with GET method that have BODY, that works fine with tests and postman
#RestController
#RequestMapping(value = "/xxx")
public class Controller {
#GetMapping({"/find"})
public LocalDateTime findMax(#RequestBody List<ObjectId> ids) {
//return sth
}
}
but when FeignClient is used to call service, instead GET request a POST request is generated (#GetMapping annotation is ignored)
#FeignClient
public interface CoveragesServiceResource extends CoveragesService {
#GetMapping({"/find"})
LocalDateTime findMax(#RequestBody List<ObjectId> ids);
}
that gives an error:
Request method 'POST' not supported

GET request technically can have body but the body should have no meaning as explained in this answer. You might be able to declare a GET endpoint with a body but some network libraries and tools will simply not support it e.g. Jersey can be configured to allow it but RESTEasy can't as per this answer.
It would be advisable to either declare /find as POST or don't use #RequestBody.

Related

Managing any HTTP request in a generic way

In my organisation, when I want to expose an API, I have to declare it with a swagger contract, same for any update, and it can take multiple weeks before the creation or change is taken into account.
That's why we've come with the idea to declare only one contract for all the APIs we need to expose, and manage the routing in an applicative reverse proxy (the request would include the necessary metadata to allow to route to the appropriate endpoint) :
{
"genericHttpRequest" : base64encodedByteArrayOfAnyHttpRequest
}
Now the question is :
how to manage this request without reimplementing HTTP ? Is it possible to put back the array of byte into a structured HttpServletRequest ?
/**
* Manage a generic request
*/
#RequestMapping(value = "/genericRequest", method = RequestMethod.POST)
public #ResponseBody void manageGenericRequest(#RequestBody GenericHttpRequestDto body) {
byte[] genericHttpRequest = body.getGenericHttpRequest();
//(...)
}
Spring will inject a HttpServletRequest if it is set as a method parameter. Furthermore, wildcard path mappings will enable the methods to be matched to every request:
#RestController
#RequestMapping("/generic-endpoint/**")
public class DemoController {
#RequestMapping
public ResponseEntity<Object> genericGetRequest(HttpServletRequest httpServletRequest) {
return ResponseEntity.ok().body(httpServletRequest.getMethod());
}
}
Optionally, you could return a ResponseEntity to gain more control over your HTTP response.

how to Add a DefaultEndpoint if No endpoint mapping is found

In my Spring boot app replacing a legacy, i have defined a webservice EndPoint.
soem of the user today comes in with payload that does nothave the namespace URI.
since namespace is not there, Spring throws No Endpoint mapping found error.
Is there a way i can add a default Endpoint so that it will get invoked if no mapping is found.
Thanks
You can try the following to create a fallback method for all request
#RequestMapping(value = "*", method = RequestMethod.GET)
#ResponseBody
public String getFallback() {
return "Fallback for GET Requests";
}
You can get more information here https://www.baeldung.com/spring-requestmapping

Content-Type is missing with Spring GET/POST method

I am new to Spring and I am trying to do the basic GET and POST method.
This is how I am trying to do the methods:
#RestController
public class DeskController {
#Autowired
private DeskDao dao;
#GetMapping("desks")
public List<Desk> getDesks() {
System.out.println(dao.findById(1L));
return dao.findAll();
}
#PostMapping("desks")
public Desk save(#RequestBody #Valid Desk desk) {
Desk deskObj = dao.save(desk);
System.out.println(deskObj);
return deskObj;
}
When I am calling the POST method like this I get the pring with the actual object that I had called it with so it is working fine, but I also get this error:
javax.ws.rs.ProcessingException: Content-Type is missing
And when trying to call GET it tells me that:
org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' not supported
I am aware that I have not included the whole code, but I will add what is needed to resolve this error since there are a lot of classes.
My questions are, what do I do against the first error and why is GET method not supported?
Two things you need to change :
Use a / to indicate that for this path you will perform an
operation. For eg : (/desks)
Use the annotation #Consumes to
indicate that this method accepts the payload in particular format. For eg : #Consumes(MediaType.APPLICATION_JSON) annotated over your save() method.

How do I implement a patch HTTP method in a custom rest controller?

I am trying to implement a patch method for my custom rest controller. The official Spring REST tutorial here has most of the HTTP methods implemented except PATCH.
So how do I implement a patch method?
Something like this should work:
#RequestMapping(method = RequestMethod.PATCH)
public MyDto createIt(#RequestBody myDto dto) {
MyDto result = service.createC(dto);
return result;
}
and dont forget to add
#RestController to your class declaration or you need to setup #ResponseBody

How to test only specific http request method available for controller method in Spring MVC?

I need to check if only specific http method is available for some url.
For example, if there is a controller like this
#Controller
public class FooController {
#RequestMapping(value = "bar", method = RequestMethod.GET)
public void bar() {/*do something*/};
...
}
For controller test I use junit(4.10), spring-test(3.2.10) and easymock(3.1).
If I write test like this
#Test
public void testBar() throws Exception {
mockMvc.perform(post("bar").session(session))
.andExpect(/*some application's default error response*/);
}
it will pass (although test calls post-method, not get-method).
So I'm looking for a proper way to make sure, that my rest resources are only avaiable by request methods specified in documentation. Two solutions came to my mind:
write tests with wrong request methods and somehow check resource is not available
add custom exception resolver to process org.springframework.web.HttpRequestMethodNotSupportedException: Request method '__' not supported and return same application default error response, but with https status 405 Method not allowed.
What would you suggest and how to check in controller test request method?
Thanks in advance.
You would need to check the status of all the request methods, you could do it using andExpect with status().isMethodNotAllowed() or status().isNotFound() depends on your needs:
Examples:
get: mockMvc.perform(get("bar").andExpect(status().isNotFound()) or mockMvc.perform(get("bar").andExpect(status().isMethodNotAllowed())
Do the same same for put, delete, ....

Categories

Resources