I have just started learning Java Spring Boot for REST API development. With below code, GET method is working fine but POST doesn't.
@RestController
@RequestMapping("/api/users")
public class UsersController {
@Autowired
private UserRepository userRepository;
@RequestMapping(method = RequestMethod.GET)
public List<User> getAll() {
return userRepository.findAll();
}
@RequestMapping(method = RequestMethod.POST)
public String saveUser() {
return "Saved";
}
}
Tested POST method in Postman app using Content-Type
as application/json
Error,
{
"timestamp": 1497116929266,
"status": 405,
"error": "Method Not Allowed",
"exception": "org.springframework.web.HttpRequestMethodNotSupportedException",
"message": "Request method 'POST' not supported",
"path": "/api/users/"
}
In the log I can see,
s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/api/users],methods=[POST]}" onto public java.lang.String com.betasquirrel.controller.UsersController.saveUser()
s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/api/users],methods=[GET]}" onto public java.util.List<com.betasquirrel.model.User> com.betasquirrel.controller.UsersController.getAll()
s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
Java and springboot version for maven,
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.4.RELEASE</version>
<relativePath/>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
Finally, solved the problem by running the project using maven command.
Instead of running project using IDE's run button, just went to the terminal in IDE and executed command
As it is a
REST
implementation, now I can access these,Work like a charm!