Java Spring Boot REST API Tutorial

In this short Tutorial you will learn how to setup a simple Spring Boot project in Java and define some REST API endpoints.

Step 1: Initialize project

First, create a new Spring Boot project using the Spring Initializer website or through an IDE such as Eclipse or IntelliJ IDEA.

Step 2: Add dependencies

Next, add the following dependencies to your pom.xml file:

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

Step 3: Create first REST API

Create a new package called “controller” and within that package, create a new class called “ExampleController”:

@RestController
@RequestMapping("/example")
public class ExampleController {

    @GetMapping("/hello")
    public String sayHello() {
        return "Hello, world!";
    }
}
Java

In the class, we have annotated it with @RestController and @RequestMapping(“/example”). The @RestController annotation is used to indicate that the class is a Spring MVC controller, and the @RequestMapping annotation is used to map the URL to the class.

Next, we have a method called sayHello() which is annotated with @GetMapping(“/hello”). This method will handle the GET request to the endpoint /example/hello and will return the string “Hello, world!”.

Step 4: Add Application

In the main application class (usually named “Application” or “SpringBootApplication”), add the following annotation to enable the REST controllers:

@SpringBootApplication
@EnableAutoConfiguration
public class MyApplication {
  public static void main(String[] args) {
    SpringApplication.run(MyApplication.class, args);
  }
}
Java

Finally, run the application by running the main method in the MyApplication class. You can test the API by sending a GET request to the endpoint http://localhost:8080/example/hello and it should return “Hello, world!”.

Step 5: Add more routes

To add more endpoints and functionality to the API, you can add more methods to the controller class, annotate them with the appropriate HTTP method (e.g. @PostMapping@PutMapping, etc.), and specify the endpoint URL in the annotation:

@PostMapping("/add")
public int addNumbers(@RequestBody int a, int b) {
        return a+b;
}
Java

This will handle the POST request to the endpoint /example/add and will return the sum of the two integers passed in the request body.

Alternatively, you can pass parameters in the URL using @RequestParam. For example:

@PostMapping("/add")
public int addNumbers(@RequestParam int a, @RequestParam int b) {
        return a+b;
}
Java

Where the call would look like this: http://localhost:8080/example/add?a=5&b=7

Finally, you can pass parameters as part of the URL using @PathVariable:

@PostMapping("/add/{a}/{b}")
public int addNumbers(@PathVariable int a, @PathVariable int b) {
        return a+b;
}
Java

Where the call would look like this: http://localhost:8080/example/add/5/7

Leave a Reply