Build RESTFul API with Spring Boot Build RESTFul API with Spring Boot

In this article, we’ll learn step by step, how to build RESTFul API with Spring Boot. We’ll also learn the RestController, HTTP response codes and best practices along the way.

1. Project Setup

For initial setup of your Spring Boot project, you should use Spring Initializr. Read here How to setup a Spring Boot project using Spring Initalizr

Assuming you chose build project as maven. A typical pom.xml for a web project look like this:-

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.3.0.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>api</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>api</name>
	<description>Build RESTFul API using Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

2. Enable Web MVC

When you are working with spring boot project, you have nothing much to do to enable spring web mvc for your project. Make sure:-

  1. You have spring-boot-starter-web dependency in your pom.xml or build.gradle
  2. You are using @SpringBootApplication on your application starter class file.

Spring Boot is opinionated, when it sees the web dependency in the classpath, it sets up all the necessary default configuration required for API development so that you can just concentrate on your business logic.

package com.example.api;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ApiApplication {

	public static void main(String[] args) {
		SpringApplication.run(ApiApplication.class, args);
	}

}

3. Build RESTFul APIs

We are creating a UserController class to build RESTFul APIs for CRUD operations. Few things to understand:-

  1. Use @RestController at class level, it helps to bind default HTTP Converters for you, e.g. when you return a User object from controller methods, it takes care of converting them in JSON.
  2. Use @RequestMapping at class level, to map APIs to URL.
  3. Use shorthand of @RequestMapping i.e. @GetMapping, @PostMapping, @PutMapping, @DeleteMapping at method level.
  4. Use @ResponseStatus at method level for appropriate HTTP Stats Code.
  5. Delegate the work to Service Layer, here using UserService
package com.example.api.controller;

@RestController
@RequestMapping("/users")
public class UserController {

	@Autowired
	private UserService userService;

	@GetMapping
	public Users getAllUsers() {
		return userService.getAllUsers();
	}

	@GetMapping("/{id}")
	public User getUserById(@PathVariable Long id) {
		return userService.getUserById(id);
	}

	@PostMapping
	@ResponseStatus(HttpStatus.CREATED)
	public Long createUser(User user) {
		return userService.createUser(user);
	}

	@PutMapping("/{id}")
	@ResponseStatus(HttpStatus.OK)
	public void updateUser(@PathVariable Long id, User user) {
		userService.updateUser(id, user);
	}

	@DeleteMapping("/{id}")
	@ResponseStatus(HttpStatus.OK)
	public void deleteUserById(@PathVariable Long id) {
		userService.deleteUserById(id);
	}
}

That’s it. Just start your application and test your APIs.

Download the source code for this example from github/springboot-api