1

I'm having a controller mapping as shown below

@RestController
@RequestMapping("/v1/connector")
public class Controller

and the API mapping as below

@GetMapping("2/auth")

when I hit the URL it's giving me the response as request URL not found. Can anyone tell why I'm getting this?

  • You are missing `@RestController` annotation along with @RequestMapping. Also, check the REST API url naming conventions , not sure `2/auth` is a good definition ! Also ensure, that this Controller class is in the same package as `Main` class (Which has `@SpringBootAnnotation` ! – Harsh Jul 12 '22 at 05:26
  • @Harsh "@RestController" is there, also edited the question, "2/auth" is actually my question, can we write like that? – rajesh shukla Jul 12 '22 at 05:33
  • Ideally, REST API definitions are descriptive verbs , numbers represent value which could be path or query parameters, I suggest you read this https://restfulapi.net/resource-naming/ & https://nordicapis.com/10-best-practices-for-naming-api-endpoints/ – Harsh Jul 12 '22 at 05:40

1 Answers1

3

@GetMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod. GET).

@RequestMapping maps HTTP requests to handler methods of MVC and REST controllers.

When you use a base path on your controller class, all controllers in that class accept URL paths that start with your given base path. In your case:

@RestController
@RequestMapping("/v1/connector")
public class Controller {
...
}

This means all of the controllers inside this class have the base path of /v1/connector and this means is a constant part of your URL and cant be changed.

So when you declare a @GetMapping("2/auth"), Spring will automatically add a / at the beginning of your path if there was no /. And your path will be http://YOUR-HOST-NAME/v1/connector/2/auth instead of http://YOUR-HOST-NAME/v1/connector2/auth.

See here for more clarification.

So If your application has paths like /v1/connector1, /v1/connector2, /v1/connector3, etc. It means the connector{n} is not constant and you must declare it on each of your controllers' methods separately.

@RestController
@RequestMapping("/v1")
public class Controller {

    @GetMapping("/connector2/auth")
    ...

    @GetMapping("/connector3/auth")
    ...

    .
    .
    .
}

  • The rest controller annotation is there, also edited the question, The issue is I'm hitting "/v1/connector2/auth" but still getting the "request URL not found" – rajesh shukla Jul 12 '22 at 05:41
  • Ok, I checked it now, and it seems spring will automatically add a slash at the beginning of `RequestMapping` if there was no slash existing. I'll update my answer. But in your case, why you don't do it this way? If `connector` is not a static path, consider extracting it from the class `@RequestMapping` annotation and declare it for each method. – Soroush Shemshadi Jul 12 '22 at 05:48