Spring Boot - @RestController Easy way for creating your REST web service

Building web services with Spring boot is quite simple, you basically have to annotate a java class with @RestController annotation.

 @RestController

public class ContactService {

}

Then, some methods of this class can be annotated with @RequestMapping, which indicates this method could be triggered by a HTTP request to the server, once it has match the defined path/URI.

 @RequestMapping(value ="/contact", method=RequestMethod.GET)

String list() {

       return "listing all contacts....";

}

Now, it is also possible to set additional parameters to be received by http requests. For this purpose we can use @PathVariable annotation, which may bind a URL parameter with a method parameter. In the value attribute of @RequestMapping annotation, you may use the {variableName} for representing Where the value will be replaced by values in the concreate use case of the REST call. You may see an example of this code below:

@RequestMapping("/contact/{id}")

       String find(@PathVariable(value="id") long id) {

             return "get a product by id="+id;

}

Another possibility is not to receive the parameter only by URL, but by HTTP request body. You may bind a HTTP request body using the annotation @RequestBody. You may see an example of its usage below. Highlighting, in this example the request mapping was also mapped to POST HTTP method.

@RequestMapping(value="/contact", method=RequestMethod.POST)

       String add(@RequestBody String contactData) {

             return "POST request with data sent in body: "+contactData;

}

Another very useful feature of defining @RequestMapping is that we can define the HTTP response type. For this purpose you just have to set the produces atribute. You may see two examples below, one producing a JSON output and the other a XML output.

@RequestMapping(value ="/contact_json", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)

       String listAsSJON() {

             return "['contact A', 'contact B','contact C']";

       }

@RequestMapping(value ="/contact_xml", method=RequestMethod.GET, produces=MediaType.APPLICATION_XML_VALUE)

       String listAsSXML() {

             return "<?xml version=\"1.0\" ?><contacts><contact>contact A</contact><contact>contact B</contact></contacts>";

        }

You may download the complete source code here:

https://github.com/rafaelqg/springboot_example/blob/main/springboot_restcontroller.java

You may watch a video class about this theme here:



Comments

Popular posts from this blog

HASHLIB: Using HASH functions MD5 and SHA256

Spread Operator

Dart: implementing Object Oriented Programming (OOP)