How to Create a Simple RESTful API in Spring Boot?

This tutorial is adapted from Web Age course Mastering Microservices with Spring Boot-and Spring Cloud.

In this tutorial we're going to build a simple "Hello World" API using Spring Framework and Spring Boot. The API will implement a single resource, "/hello-message" that returns a JSON object that contains a greeting.

You need to install  Eclipse and Maven before you start working on this tutorial.

Part 1 - Create a Maven Project

We're going to start from scratch on this project, with an empty Apache Maven project, and add in the dependencies that will make a Spring Boot project with a core set of capabilities that we can use to implement our "Hello World" API.

1. Open Eclipse.

2. In the Workspace Launcher dialog, enter 'C:\Workspace' in the Workspace field, and then click OK.

3. Close the Welcome panel by clicking on the 'X':

4. From the main menu, select File → New → Maven Project.

5. In the New Maven Project dialog, click on the checkbox to select "Create a simple project (skip archetype selection)", and then click Next.

6. Enter the following fields:

Group Id: com.webage.spring.samples

ArtifactId: helloAPI

Leave all the other fields at their default values.

7. When the dialog looks like below, click Finish.

Part 2 - Configure the Project as a Spring Boot Project

The steps so far have created a basic Maven project. Now we'll add the dependencies to make a Spring Boot project.

1. Expand the helloAPI project in the Project Explorer.

2. Double-click on pom.xml to open it.

3. At the bottom of the editor panel, click the pom.xml tab to view the XML source for pom.xml.

4. Insert the following text after the "<version>...</version>" element, and before the closing "</project>" tag.

<parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>1.4.2.RELEASE</version>
</parent>

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

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

The entries above call out the Spring Boot Starter Parent project as the parent to this project, then call out the Spring Boot Starter Web dependencies. Finally the <build> element configures the Spring Boot Maven Plugin, which will build an executable jar file for the project.

5. Save the file by pressing Ctrl-S or selecting File -> Save from the main menu.

Part 3 - Create an Application Class

Spring Boot uses a 'Main' class to startup the application and hold the configuration for the application. In this section, we'll create the main class.

1. In the Project Explorer, right-click on src/main/java and then select New → Package.

2. Enter 'com.webage.spring.samples.hello' in the Name field, and then click Finish.

3. In the Project Explorer, right-click on the newly-created package and then select New → Class.

4. In the New Java Class dialog, enter 'HelloAPI' as the Name, and then click Finish.

5. Add the '@SpringBootApplication' annotation to the class, so it appears like:

@SpringBootApplication
public class HelloAPI {

6. Add the following 'main' method inside the class:

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

7. The editor is probably showing errors due to missing 'import' statements. Press Ctrl-Shift-O to organize the imports.

8. Save the file.

9. The helloAPI project node may show a small red 'x' to indicate an error. If so, right-click on the helloAPI project and then select Maven → Update Project, and then click OK in the resulting dialog.

10. In the Project Explorer, right-click on either the helloAPI project node or the 'pom.xml' file and then select Run As → Maven Install.

Note. If fails building try again and the second time should works.

The console should show a successful build. This ensures that we don't have any typos in the pom.xml entries we just did.

Now all we need to do is add a resource class and a response class.

Part 4 - Implement the RESTful Service

In this part of the tutorial, we will create a response class and a RESTful resource class,

1. In the Project Explorer, right-click on src/main/java and then select New → Package.

2. Enter 'com.webage.spring.samples.hello.api' in the Name field, and then click Finish.

3. In the Project Explorer, right-click on the newly-created package and then select New → Class.

4. In the New Java Class dialog, enter 'HelloResponse' as the Name, and then click Finish.

5. Edit the body of the class so it reads as follows:

package com.webage.spring.samples.hello.api;

public class HelloResponse {
	String message;
	public HelloResponse(String message) {
		super();
		this.message = message;
	}
	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}	
	
}

6. Save the file.

7. In the Project Explorer, right-click on the 'com.webage.spring.samples.hello.api' package and then select New → Class.

8. In the New Java Class dialog, enter 'HelloResource' as the Name, and then click Finish.

9. Add the following 'getMessage' method inside the new class:

public HelloResponse getMessage() {
	return new HelloResponse("Hello!");
}

Spring Boot recognizes and configures the RESTful resource components by the annotations that we're about to place on the resource class that we just created.

10. Add the '@RestController' annotation to HelloResource, so it looks like:

@RestController
public class HelloResource {

11. Add the '@GetMapping' annotation to the 'getMessage' method, so it looks like:

@GetMapping("/hello-message")
public HelloResponse getMessage() {

12. Organize the imports by pressing Ctrl-Shift-O.

13. Save all files by pressing Ctrl-Shift-S.

14. In the Project Explorer, right-click on either the helloAPI project node or the 'pom.xml' file and then select Run As → Maven Install.

Note. If fails building try again and the second time should works.

The console should show a successful build.

Part 5 - Run and Test

That's all the components required to create a simple RESTful API with Spring Boot. Now let's fire it up and test it!

1. In the Project Explorer, right-click on the HelloAPI class and then select Run as → Java Application.

2. If the Windows Security Alert window pops up, click on Allow Access.

3. Watch the Console panel. At the bottom of it, you should see a message indicating that the 'HelloAPI' program has started successfully:

4. Open the Chrome browser and enter the following URL in the location bar:

http://localhost:8080/hello-message

5. You should see the following response:

Notice that the response is in the form of a JSON object whose structure matches the 'HelloResponse' class contents.

6. Close the browser.

7. Click on the red 'Stop' button on the Console panel to stop the application.

8. Close all open files.

Part 6 - Review

In this tutorial, we setup a rudimentary Spring Boot application. There are a few things you should notice:

  • There was really very little code and configuration required to implement the very simple RESTful API.

  • The resulting application runs in a standalone configuration without requiring a web or application server. It opens its own port on 8080.

  • Although the Eclipse IDE is providing some nice features, like type-ahead support and automatic imports, the only tool we really need is a build tool that does dependency management (e.g. Apache Maven).

 

Karandeep Kaur August 29, 2019

Leave a Reply

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

Web age solutions blog Zones