We will assume that we already have the previous configuration of the project done and we have added the web dependencies within our pom.xml.
Imagine that we want to create an endpoint following a rest architecture so we have defined that the name of our resource is coffee and we are doing a GET operation to bring data about this resource, the endpoint would be the following:
www.miurlfavorita.com/coffee/{id}
where {id}
is a number that identifies our resource and comes to be the same as spring maps on our @PathVariable
tag. To perform this mapping correctly, in our controller we define the method that generates the endpoint:
@ResponseBody
@GetMapping(produces = [MediaType.APPLICATION_JSON_UTF8_VALUE], value = '/{idCoffee}')
CoffeeResponse getCoffeeInfo(
@PathVariable('idCoffee') String idCoffee
) {
//Lógica que hace lo que sea
}
Let's analyze this method for a moment, if you look at the code you've shared, you use the @PathVariable
tag but in your @RequestMapping
you do not indicate inside the endpoint where those variables are so Spring does not know where they come from . If you look at the method I use the @GetMapping
tag that does the same as @RequestMapping
but by default the http method is already get what is much more readable and I recommend its use (there are also @PostMapping
, @PutMapping
... etc).
Within @getMApping
you can see that I have the {idCoffee}
between braces what tells Spring that in this part of the url what is coming is not the literal "idCoffee", it comes a "variable path" that has to map in the corresponding parameter.
Finally, within the url that I have defined, where do I indicate to Spring the / coffee that indicates the name of the resource? This is indicated in the class and not in the method since it is not a good practice. Ideally, each controller should refer to a particular resource and all the methods should be different operations on it, so my class would be defined as such.
@RequestMapping(value = '/coffee')
@RestController
class BestCoffeeClassEver {
...
}
In this case I use the @RequestMapping
without any type of operation since I am at the class level so all the endpoints that I generate in that class will be url / coffee / (whichever it generates in each method).