Creating a simple REST API using Spring Boot can be a smooth process, and it is entirely possible to get it done in under 10 minutes. Here’s a step-by-step guide to building your first REST API:
1. Setup Your Spring Boot Project
- Go to Spring Initializr.
- Configure the project:
- Project: Maven.
- Language: Java.
- Spring Boot Version: Choose the latest stable version.
- Dependencies: Add Spring Web (this adds support for creating a REST API).
- Click to download the project as a
.zip
file.Generate
- Extract the file, then open it in your favorite IDE like IntelliJ IDEA.
2. Create a REST Controller
A REST controller handles HTTP requests and maps them to methods. You will use the @RestController
annotation to create a REST API in Spring Boot.
Create a file under src/main/java/com/example/demo/
named : HelloWorldController.java
package com.example.demo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class HelloWorldController {
@GetMapping("/hello")
public String helloWorld() {
return "Hello, World!";
}
}
- Annotations Explained:
@RestController
: Combines@Controller
and@ResponseBody
, enabling REST-specific behavior.@RequestMapping
: Specifies the base path for this controller (e.g.,/api
).@GetMapping
: Handles HTTP GET requests for the/hello
sub-endpoint.
3. Run Your Application
- Run your application by navigating to the
DemoApplication
class and executing the method (Run
button in IntelliJ).main
- By default, your application will start on port 8080.
4. Test Your REST API
- Open a browser or use a tool like Postman or
curl
to test your REST API. - Navigate to http://localhost:8080/api/hello.
- If everything is set up properly, you will see this response:
Hello, World!
5. (Optional) Add Another Endpoint Returning JSON
If you want to return a JSON response, create a new endpoint:
@GetMapping("/greet")
public Greeting greetUser() {
return new Greeting("Welcome to Spring Boot!");
}
Create a new class Greeting.java
under the same package:
package com.example.demo;
public class Greeting {
private String message;
public Greeting(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
- Response from http://localhost:8080/api/greet:
{
"message": "Welcome to Spring Boot!"
}
6. Complete!
Congratulations, you’ve successfully created your first REST API with Spring Boot!