DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Coding
  3. Frameworks
  4. Spring Boot RESTful Web Service Example

Spring Boot RESTful Web Service Example

Does your Java app look sluggish and tired all the time? Learn how to make sure your Spring Boot application is well rested!

Abhijit Pritam Dutta user avatar by
Abhijit Pritam Dutta
CORE ·
Jul. 11, 18 · Tutorial
Like (28)
Save
Tweet
Share
266.70K Views

Join the DZone community and get the full member experience.

Join For Free

Prerequisites for this project:

  1. If you have Eclipse, download the STS plug-in from here.

  2. If you don’t have Eclipse, download STS from here.

  3. Download the latest JDK from here. 

In this article, I am going to explain how to develop a RESTful Spring Boot project, step-by-step.

The first example I am going to explain is HTTP GET requests and the second example will be about HTTP POST requests and, in both, the example message format will be in JSON representation. You can download the project from https://github.com/prateekparallel/spring-boot-rest

Let’s start: 

1. First, from the File menu select "New"  and then "other" and from wizard expand "Spring Boot" and select ‘Spring Starter Project’ (File->New->other->wizard->Spring Starter Project)

Image title

Now select next and provide the below information and click the Finish button.

Image title

Now you can see the below file structure in your project's explorer window.

Image title

Now, look that the SpringBootRestApplication.java file which is created by the STS plug-ins.

package com.bhaiti.server.main;

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

@SpringBootApplication
public class SpringBootRestApplication {

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

This is a Spring Boot main class. A Spring Boot REST application loads through this class. We can also see that this class is created with the annotation @SpringBootApplication . As per the Spring documentation, the annotation @SpringBootApplication is equivalent to using @Configuration, @EnableAutoConfiguration, and @ComponentScan, and these annotations are frequently used together. Most of the time in Spring Boot development, the main class is always annotated with all three of these important annotations.

So we are going to modify the @SpringBootApplication (given below in the Java class) with a component path. Without that, the application cannot find out the controller classes. We will learn more about controller classes in a few minutes.

@SpringBootApplication(scanBasePackages = {"com.bhaiti"})

publicclass SpringBootRestApplication {
       publicstaticvoid main(String[] args) {
              SpringApplication.run(SpringBootRestApplication.class, args);
       }
}

2. To model the welcome representation, we are going to create a resource representation class here.             

First, we will create package, com.bhaiti.beans, and add the class into that package like below:

a) Right-click on the project and select New and then package. Enter the above package name and click Finish.

Image title

b) Now, right click on the packagecom.bhaiti.beans and select New->class and provide the class name, Welcome, like below:

Image title

In the empty class, just copy and paste the below code: 

package com.bhaiti.beans;

public class Welcome {

public Welcome(String message) {
super();
this.message = message;
}

private final String message;

public String getMessage() {
return message;
}

}

So the above Welcome class is a resource representation class for a welcome message. Spring uses the Jackson JSON library to automatically marshal instances of type Welcome into JSON.

Now we will introduce a controller and that will serve Welcome. In Spring’s approach to building RESTful web services, HTTP requests are handled by a controller. Controller classes/components are easily identified by the @RestController annotation, and the below WelcomeController will handle GET requests for  /welcome/user by returning a new instance of the Welcome class.

Now just follow step 2a and 2b and create the package com.bhaiti.rest.controllerand add the class WelcomeController to it and import the class Welcome.

import com.bhaiti.beans.Welcome;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class WelcomeController {

private static final String welcomemsg = "Welcome Mr. %s!";

    @GetMapping("/welcome/user")
    @ResponseBody
    public Welcome welcomeUser(@RequestParam(name="name", required=false, defaultValue="Java Fan") String name) {
        return new Welcome(String.format(welcomemsg, name));
    }

}

The @RequestMapping annotation maps all HTTP operations by default and, in this example, it ensures that HTTP requests to /welcome/user are mapped to the Welcome() method.

Now we are done with everything for a GET RESTful call. Let’s test this application first. After the test, we will learn about POST calls as well.

To compile this project with Maven, we will add the below information into the POM file:

<dependencies>

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

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

<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>
</dependency>

</dependencies>

And we'll also add tje below information for the property file for this project under the build section of our POM.xml file (to change the port number at the moment):

       <resources>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering>
        </resource>
        </resources>

Now create a property file, application.properties, under C:\Projects\spring-boot-rest\src\main\resources (this is my project location, in your case this folder/directory is situated under your project folder/directory. So search for ..\src\main\resources and create the above file and add the below lines to it.

server.port=8083 

spring.profiles.active=@spring.profiles.active@ 

3. Now open the command prompt window and go to the project home directory in the command prompt. In my case, it looks like this:

cd C:\Projects\spring-boot-rest 

mvnw clean package 

If everything goes fine, you can see the below result:

Image title

Now run the server:- 

java -jar target\spring-boot-rest-0.0.1-SNAPSHOT.jar 

Once the server starts successfully, open your browser and put the below URL in the address bar and press enter. Now you can see the below information:

http://localhost:8083/welcome/user?name=Abhijit (here I have put my name, you can change it to yours, this is also optional you can just try it with http://localhost:8083/welcome/user).

Image title

Up to now, we have learned how to implement a RESTful GET request. Now we will learn how to implement a POST request.

Our POST request will be for a Student Registration. For that, first, we are going to create a resource representation class, StudentRegistration, to capture a request and StudentRegistrationReply to send a response from the POST call.

1. Follow step 2b create both classes under the package com.bhaiti.beans.

package com.bhaiti.beans;

public class StudentRegistration {

String name;
int age;

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}

}


package com.bhaiti.beans;

public class StudentRegistrationReply {

String name;
int age;
String registrationNumber;
String registrationStatus;

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getRegistrationNumber() {
return registrationNumber;
}
public void setRegistrationNumber(String registrationNumber) {
this.registrationNumber = registrationNumber;
}
public String getRegistrationStatus() {
return registrationStatus;
}
public void setRegistrationStatus(String registrationStatus) {
this.registrationStatus = registrationStatus;
}

}

1. Now it's time to introduce the controller class to handle the POST request.

Follow step 2b and add the below controller class in the package.

package com.bhaiti.rest.controller;
import com.bhaiti.beans.*;

/**
 * @author prate
 *
 */
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class StudentRegisterController {

@RequestMapping(method = RequestMethod.POST, value="/register/student")
@ResponseBody
StudentRegistrationReply registerStudent(@RequestBody StudentRegistration studentregd) {

StudentRegistrationReply stdregreply = new StudentRegistrationReply();
stdregreply.setName(studentregd.getName());
stdregreply.setAge(studentregd.getAge());
stdregreply.setRegistrationNumber("12345678");
stdregreply.setRegistrationStatus("Successful");
return stdregreply;

}

}

Stop the server (by using Control-C), compile the code, and run the server again.

Now to test our app, we will use SOAPUI. You can download SOAPUI from here.

In the SOAPUI tool, choose: File->New REST Project.

And copy-paste the below URL:

http://localhost:8083/register/student

Select POST and paste the data below in the Media Type Sub window

{
            "name": "Abhijit!",
            "age": 25
}

Image title

Now click the green arrow and see the response from the server.

Spring Framework Spring Boot REST Web Protocols Web Service

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • 10 Most Popular Frameworks for Building RESTful APIs
  • Use AWS Controllers for Kubernetes To Deploy a Serverless Data Processing Solution With SQS, Lambda, and DynamoDB
  • Leverage Lambdas for Cleaner Code
  • Creating a Personal ReadMe for Scrum Masters With ChatGPT

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: