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?

6
  • Looks like your HTTP server is rewriting requests without the trailing slash and sending a redirect, substituting GET for POST. Check your server config. Commented Mar 12, 2018 at 7:41
  • @JimGarrison What configs are you referring to? I start my app as mvn spring-boot:run, so it's embedded Tomcat. I don't have any additional configs. Commented Mar 12, 2018 at 7:44
  • Hmm... based on this question it looks like it's not designed to do that redirect.... so this is beyond my expertise. Sorry. Commented Mar 12, 2018 at 7:48
  • I found the answer from here. stackoverflow.com/a/45258671/331946 Commented Aug 24, 2020 at 12:47
  • @htshame Remove the "update" part + add it as an answer! Commented Apr 8, 2021 at 12:26

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.