<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.2.1.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> <properties> <java.version>1.8</java.version> </properties> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>This is the minimal configuration for a Spring Boot web application. From the JAR files downloaded by Maven, you can see Spring framework provides its own API for RESTful web services (it doesn’t implement JAX-RS specification). It also uses Jackson library for serialization of Java objects to JSON and vice-versa.TIP: Use Spring Boot DevTools for automatic restart so you don't have to manually restart the application during development.
package net.codejava; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { @RequestMapping("/hello") public String hello() { return "Hello World RESTful with Spring Boot"; } }This is, perhaps the simplest form of a RESTful webservices API with Spring Boot. The @RestController annotation specifies this class will handle requests and produce responses following REST style. It does all the default configurations so you can start coding your API quickly.
package net.codejava; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }Now, we’re ready to test our first Spring Boot RESTful web services application.
Tomcat started on port(s): 8080 (http) with context path ''
That means your Spring Boot RESTful application is deployed on Tomcat server listening on port 8080. Now you can type the URL http://localhost:8080/hello into your web browser, and get the following page:This means our RESTful API has been invoked successfully. You can use the following curl command to test:curl http://localhost:8080/helloAnd response from the server:
Hello World RESTful with Spring BootNext, let’s update the HelloController class to understand the basic APIs provided by Spring framework for simplifying RESTful webservices API development. Check this article to learn more about API testing using curl command.
@RequestMapping("/hello") public String hello(@RequestParam(name = "name", defaultValue = "World") String name) { return "Hello " + name; }The @RequestParam annotation binds the value of the request parameter named “name” to a parameter of this method. If the query parameter is absent, then the default value “world” is used.You must stop the application and run again. Type the following command to test:
curl http://localhost:8080/hello?name=NamThe server responds:
Hello Nam
Spring Boot REST APIs Ultimate Course
Hands-on REST API Development with Spring Boot: Design, Implement, Document, Secure, Test, Consume RESTful APIs
@RequestMapping(value = "/hello", method = RequestMethod.POST)To simplify RESTful APIs development, Spring provides the annotations @GetMapping, @PostMapping, @PutMapping and @DeleteMapping corresponding to HTTP methods GET, POST, PUT and DELETE. So a typical REST controller will look like this:
@RestController public class ResourceController { @GetMapping("/resources") // method that returns all items @GetMapping("/resources/{id}") // method that returns a specific item @PostMapping("/resources") // method that creates a new item @PutMapping("/resources/{id}") // method that updates an item @DeleteMapping("/resources/{id}") // method that deletes an item }
package net.codejava; public class Product { private int id; private String name; private float price; // constructors... // getters... // setters... }Then the following method will return JSON representation of a Product object:
@GetMapping("/getproduct") public Product getProduct() { return new Product(1, "iPhone", 999.99f); }Command to test with curl:
curl http://localhost:8080/getproductServer responds:
{"id":1,"name":"iPhone","price":999.99}You can also return a collection of Java objects and Spring converts to JSON string neatly.
@PostMapping("/addproduct") public void addProduct(@RequestBody Product product) { System.out.println(product); }And you can test using the following curl command:
curl -X POST -H "Content-Type: application/json" -d "{\"id\":1,\"name\":\"Kindle Fire\",\"price\":199}" http://localhost:8080/addproductFor validating data in the request's body (payload), see this article: Spring Boot REST API Request Validation Examples
@PostMapping(value = "/update", consumes = {MediaType.APPLICATION_JSON_VALUE})Then the client must send request with content type corresponding to the type specified, e.g. application/json in this example.
@GetMapping(value = "/getproduct", produces = {MediaType.APPLICATION_JSON_VALUE})Then the content type of the response will be set according to the type specified, e.g. application/json in this example.
@GetMapping("/products/{id}") public ResponseEntity<Product> getProduct(@PathVariable int id) { // find the product by id if (found) { return new ResponseEntity<Product>(productObject, HttpStatus.OK); } else { return new ResponseEntity<Product>(HttpStatus.NOT_FOUND); } }As you can see, this method will return a response with HTTP status code 200 (OK) and JSON representation of the Product object if a product found with the given ID. Else return HTTP status code 404 (Not Found).That’s how to get started with RESTful webservices API development using Spring Boot. You have learned how to create a hello world Spring Boot REST application and the fundamental APIs for developing REST APIs with Spring. You can download the sample project attached below, or clone the project from this GitHub repo.You can also watch the video version of this tutorial below: What's Next? I recommend you this one: Spring Boot RESTful CRUD API Examples with MySQL database