Skip to content
  • About Us
  • Contact Us
  • Disclaimer
  • Privacy Policy
  • Terms and Conditions

Simplified Learning Blog

Learning made easy

  • Java
    • Core Java Tutorial
    • Java 8
    • What is Rest API in java
    • Spring Framework
    • Type Casting in Java | 2 types Implicit and explicit casting
    • Spring Boot Tutorial
      • Spring Boot Rest API Example complete guide
    • Top 50 Java Interview Questions
    • JUnit 5 Tutorial
      • Assertall in JUnit 5
      • Assertions in JUnit 5
    • Java Thread Tutorials
      • How to create thread in Java
      • Multithreading in java
      • Daemon Thread in Java | How to create daemon thread in java
      • Top 40+ Multithreading interview questions
  • AWS
    • What is AWS (Amazon Web Services)
    • AWS IAM (Identity and Access Management)
    • AWS SNS | What is SNS
    • What is SQS | AWS SQS (Simple Queue Service)
    • What is AWS Lambda
    • Top 10 AWS Lambda interview questions
  • Java Codes
  • Software Architecture
    • Software Architecture Performance
    • Performance Principles of Software Architecture
    • System Performance Objective
  • Spring Boot Tutorial
  • Tools
    • JSON Formatter and Validator
  • Tech Blogs
    • Java 21 New Features
    • Is Java Dead? Is java dead, 2023 ?
    • New Features in Java 17
  • Toggle search form

Spring Boot Rest API Example complete guide

Posted on February 10, 2023February 27, 2024 By Admin No Comments on Spring Boot Rest API Example complete guide

In rest API tutorial of Spring Boot Rest API, we are going to learn spring boot rest API with example. How to create spring boot restful web service in Java.

Table of Contents

Toggle
  • Spring Boot Rest API @RestController:
  • @GetMapping
  • Creating Users: Post Mapping ():
  • Spring Boot Rest API Complete source code:
  • FAQ on Spring Boot

What is rest API ? You can learn here. Let’s go through the code snippet.

We are going to use spring boot for this tutorial. If you are new to spring boot, please refer to creating first spring boot application blog.

Spring Boot Rest API @RestController:

First, we need to create a rest controller for our test case of User Object (we have created a POJO class called User). e.g. User Controller like this: Don’t worry, we will provide full source code for this tutorial at the end.

@RestController
public class UserController {----}

@RestController: annotation create rest controller for us which will handle a lot of things internally like mapping of request and response object based on type.

Then we will create one method, getUser to get the user object:

//   @RequestMapping(path = "/user", method = RequestMethod.GET) alternative way 
    @GetMapping("/user")
    public User getUser(){
        return userService.getUser("1");
    }

Output of the above: hit localhost:8080/user (as per your port specified)

Spring Boot Rest API
Get Mapping to return single user

@GetMapping

@GetMapping(“/user”) you can also use it like this @RequestMapping(path = “/user”, method = RequesrtMethod.GET)

Here, what we are doing is that we are using @GetMapping annotation which defines the mapping of request and its get call, similarly we can use @PostMapping for post method.

@GetMapping is actually shortcut of @RequestMapping(method = RequestMethod.GET) same for @PostMapping.

In the above code snippet, what we’re doing is that we mapped GET /user request to getUser() method, which will return the User whose ID is 1. Note that for simplicity we have hardcoded these IDs and some of the database calls, later we will add more functionalities in the same code.

RequestMethod is an ENUM provided by spring framework which contains Http request methods.

public enum RequestMethod {

	GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE

}

Now, let’s create another get mapping which will return the list of users rather than a single user.

    @GetMapping("/users")
    public List<User> getUsers(){
        return userService.getUsers();
    }

Here, we are calling get mapping with /users, which is returning the list of users.

O/P:

Spring Boot Rest API
User List

What is userService here ? For this tutorial we have created a dummy service which will return the data which is mock data, later will connect service layer to DAO and get the data of users from database. Here is the code snippet of the same.

Interface UserService :

public interface UserService {
    User createUser(User user);
    User getUser(String userId);
    List<User> getUsers();
}

UserServiceImpl:

@Service
public class UserServiceImpl implements UserService{
    @Override
    public User createUser(User user) {
        //we are just returning dummy user here
        return createDummyUser();
    }

    @Override
    public User getUser(String userId) {
        return createDummyUser();
    }

    private User createDummyUser(String name, String id, String address){
        return new User(name,"12","TEST ADDRESS");
    }

    private User createDummyUser(){
        return new User("SLB","12","TEST ADDRESS");
    }

    @Override
    public List<User> getUsers() {
        //later will get all these details from db/file/service, etc
        ArrayList<User> users = new ArrayList<>();
        users.add(createDummyUser("abc","2","test1"));
        users.add(createDummyUser("tes","3","test1"));
        users.add(createDummyUser("res","4","test1"));
        users.add(createDummyUser("tse","5","test1"));

        return users;
    }
}

@Service Annotation is used to mark is as service provider class where in these classes provides some business related functionalities. Spring context will autodetect these classes when annotation based configuration and XML based configuration is used.

Creating Users: Post Mapping ():

Post mapping is used to create or generate new objects/entities. In our example, we will use it to create a user object.

    @PostMapping(value = "/user")
    public User getUser(@RequestBody(required = true)  User user){
        System.out.println("executing post user with " + user.toString());
        userService.createUser(user);
        return user;
    }

In the above code snippet, we are using @PostMapping to create user. We are also using @RequestBody for sending user object as a part of the body of the request.

To hit this, we need to use postman. Here, is the sample request and response of the request.

REST API TUTORIAL
Postman-post user request

Output:

REST API TUTORIALS
Output of post user request

Spring Boot Rest API Complete source code:

In pom.xml add below dependency:

	<dependency>
		<groupId>org.projectlombok</groupId>
		<artifactId>lombok</artifactId>
		<version>1.18.26</version>
		<scope>provided</scope>
	</dependency>

Controller:

package com.slb.spring.boot.controller;


import com.slb.spring.boot.domain.User;
import com.slb.spring.boot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class UserController {

    @Autowired
    UserService userService;

   //@RequestMapping(path = "/user", method = RequestMethod.GET) alternative way
    @GetMapping("/user")
    public User getUser(){
        return userService.getUser("1");
    }

    @GetMapping("/users")
    public List<User> getUsers(){
        return userService.getUsers();
    }

    @PostMapping("/user")
    public User getUser(@RequestBody(required = true)  User user){
        System.out.println("executing post user with " + user.toString());
        userService.createUser(user);
        return user;
    }

}

Service :

package com.slb.spring.boot.service;

import com.slb.spring.boot.domain.User;

import java.util.List;

public interface UserService {

User createUser(User user);
User getUser(String userId);
List<User> getUsers();
}

Service Implementation:

package com.slb.spring.boot.service;

import com.slb.spring.boot.domain.User;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl implements UserService{
    @Override
    public User createUser(User user) {
        //we are just returning dummy user here
        return createDummyUser();
    }

    @Override
    public User getUser(String userId) {
        return createDummyUser();
    }

    private User createDummyUser(String name, String id, String address){
        return new User(name,"12","TEST ADDRESS");
    }

    private User createDummyUser(){
        return new User("SLB","12","TEST ADDRESS");
    }

    @Override
    public List<User> getUsers() {
        //later will get all these details from db/file/service, etc
        ArrayList<User> users = new ArrayList<>();
        users.add(createDummyUser("abc","2","test1"));
        users.add(createDummyUser("tes","3","test1"));
        users.add(createDummyUser("res","4","test1"));
        users.add(createDummyUser("tse","5","test1"));

        return users;
    }
}

User Class:

package com.slb.spring.boot.domain;

import lombok.Builder;
import lombok.Data;

@Data
public class User {

    String name;
    String id;
    String address;

    public User(String name, String id, String address) {
        this.name = name;
        this.id = id;
        this.address = address;
    }
}

Checkout GitHub for Complete Code of the tutorial.

FAQ on Spring Boot

  1. What Are the Advantages of Spring Boot?
    • One of the main advantages of using Spring Boot is its ease in creating production-grade applications quickly and with minimal setup. This is accomplished via features like auto-configuration that remove the need for manual configuration; additionally, Spring Boot comes preloaded with features like an embedded web server and actuator endpoint that make creating production applications simple and fast.
  2. How Can I Begin Working With Spring Boot?
    • Getting started with Spring Boot is relatively straightforward. The first step should be adding Spring Boot starter dependencies (pom.xml for Maven projects). After this step has been completed, you can then begin writing application code using its features – Spring Boot also offers numerous samples and guides online that can help get you going quickly.
  3. How Can I Deploy a Spring Boot Application?
    • There are various ways of deploying your Spring Boot app, depending on your specific requirements. One option is packaging it as a jar file and running it using Java’s -jar command; alternatively you could deploy it directly onto a cloud platform such as Heroku or AWS; Spring Boot also provides support for containerization using Docker.
  4. How Can I Customize Spring Boot for My Specific Needs?
    • Spring Boot offers various ways of customizing its application to fit your specific requirements. One option is using application.properties or application.yml files to set application-wide configuration properties. Another way is creating configuration classes that implement the EnvironmentPostProcessor interface so as to set configuration properties programmatically.
  5. How Can I Test My Spring Boot App ?
    • Spring Boot offers several testing solutions, such as JUnit and Mockito. Furthermore, its Spring Boot Test framework makes writing integration tests for your application simpler with features such as auto-configuration and embedded servers making setting up test environments straightforward.

Related

Java Threads Tags:rest ap[i tutorial, Rest API

Post navigation

Previous Post: What is Rest API in java
Next Post: JSON Formatter and Validator

More Related Articles

Java Thread Tutorials Java Threads
Top 40+ Multithreading interview questions Java Threads
Multithreading in java Java Threads
Daemon Thread in Java | How to create daemon thread in java Java Threads
How to create thread in Java Java Threads

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • Top 50 Java Coding Interview Questions and Answers (2025 Updated)
  • Java Record Class Explained: Simple, Immutable Data Carriers
  • Java Convert int to String – 5+ Methods with Examples
  • String to Integer Conversion in Java | Java convert string to int
  • PDF to JSON Convertor

Recent Comments

No comments to show.

Copyright © 2025 Simplified Learning Blog.

Powered by PressBook Green WordPress theme