Spring framework is programmer’s favorite application framework for developing enterprise Java applications and REST is the de facto standard for developing web-based APIs. In this tutorial, I will help you get started with developing RESTful webservices APIs with Java and Spring framework using Spring Boot. You will learn how easy it is to create your first, a kind of hello world REST API with Spring.

To follow this tutorial, you must have JDK (version 1.8 or newer) and an IDE (Eclipse, NetBeans, or IntelliJ IDEA) installed on your computer. Having curl program is an option to test RESTful API.

 

1. Create Maven project and specify Spring Boot dependencies

First, create a Maven project and specify the following configuration in the pom.xml file:

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

 

2. Create your first hello world RESTful Web Services Spring Boot application

Create the HelloController class with the following code:

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.



The hello() method will handles HTPT GET request with URL ending with /hello. It simply returns a hello world text message.

Next, create the main class to run your Spring Boot application as follows:

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.


3. Test your first Spring Boot RESTful Web Services

Run the Application class as a Java application, you should see Spring Boot logo appears and some logging messages outputted to the console like this:

spring boot restful start up

Notice this line:

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:

test spring boot restful chrome

This means our RESTful API has been invoked successfully. You can use the following curl command to test:

curl http://localhost:8080/hello
And response from the server:

Hello World RESTful with Spring Boot
Next, 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.


4. How to read request parameter

Update the hello() method as below:

@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=Nam
The 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

 

5. How to handle different HTTP methods

Basically you can specify a specific HTTP method using the method attribute of the @RequestMapping annotation (default is GET), for example:

@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
}
 

6. How to return JSON Response

Serialize Java objects to JSON string and vice-versa is done automatically by Spring (thanks to JSON Jackson library). Create a simple domain model class as below:

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/getproduct
Server responds:

{"id":1,"name":"iPhone","price":999.99}
You can also return a collection of Java objects and Spring converts to JSON string neatly.


7. How to read JSON data

You can use the @RequestBody annotation to bind JSON data sent from client as a Java object, for example:

@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/addproduct
For validating data in the request's body (payload), see this article: Spring Boot REST API Request Validation Examples

 

8. How to specify content type of the request

To explicitly specify the content type accepted by the server, you can use the consumes attribute of a @XXXMapping annotation. For example:

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

 

9. How to specify content type of the response

To explicitly specify the content type of the response sent to the client, you can use the produces attribute of a @XXXMapping annotation. For 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.

 

10. How to specify HTTP status code for the response

You can use the ResponseEntity class to explicitly produces a response with specific HTTP status, including JSON data in the response body. Consider the following method:

@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). It's recommended to follow best pratices when returning HTTP status code from your REST APIs.

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

 

Related Web Services Tutorials:

 

Other Spring Boot Tutorials:

 


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.



Attachments:
Download this file (SpringBootHelloRest.zip)SpringBootHelloRest.zip[Sample Spring Boot RESTful hello world project]12 kB

Add comment

   


Comments 

#1NASSER ALI2022-04-03 16:29
Are you work with session, and Realm: Usernames, passwords, and roles for the session using H2 database
Quote