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

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="" xmlns:xsi=""
		<relativePath/> <!-- lookup parent from repository -->
	<description>Build RESTFul API using Spring Boot</description>






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;

public class ApiApplication {

	public static void main(String[] args) {, 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;

public class UserController {

	private UserService userService;

	public Users getAllUsers() {
		return userService.getAllUsers();

	public User getUserById(@PathVariable Long id) {
		return userService.getUserById(id);

	public Long createUser(User user) {
		return userService.createUser(user);

	public void updateUser(@PathVariable Long id, User user) {
		userService.updateUser(id, user);

	public void deleteUserById(@PathVariable Long id) {

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

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