2

I have a spring-boot rest api.

In my application.properties I have:

server.port=8100
server.contextPath=/api/users

There's a controller:

@RestController
@RequestMapping("")
public class UserService {
    @RequestMapping(value = "", method = POST, produces = "application/json; charset=UTF-8")
    public ResponseEntity<UserJson> create(@RequestBody UserJson userJson) {
    ...
    }
}

When I call:

POST http://localhost:8100/api/users/ notice the trailing slash (with user's json) - create method executes fine.

But when I call:

POST http://localhost:8100/api/users without trailing slash (with user's json) - I receive 405 error:

{ "timestamp": 1520839904193, "status": 405, "error": "Method Not Allowed", "exception": "org.springframework.web.HttpRequestMethodNotSupportedException", "message": "Request method 'GET' not supported", "path": "/api/users/" }

I need my URL without trailing slash, just .../api/users, and why it's being treated as GET method?

htshame
  • 6,599
  • 5
  • 36
  • 56

1 Answers1

1

If I change server.contextPath to server.contextPath=/api and @RequestMapping in my RestController to @RequestMapping("/users") everything works fine. create() method is being called with and without of trailing slash at the end on the URL.

htshame
  • 6,599
  • 5
  • 36
  • 56
  • Any particular reason you set the contextPath at all? A request mapping for /api/users would be what I would do. Actually I would do /api/users/v1 because future you will thank you for introducing API versions sooner rather than later. – Gimby Apr 08 '21 at 13:24
  • I have a pretty big app, so we need a contextPath for the common API URl prefix. I also have /v1 and /v2 prefixes, but they are on the @RestController levels now. – htshame Apr 08 '21 at 14:28