Building Your First REST API with Spring Boot in Under 10 Minutes

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

  1. Go to Spring Initializr.
  2. 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).
  3. Click to download the project as a .zip file. Generate

  4. 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

  1. Run your application by navigating to the DemoApplication class and executing the method (Run button in IntelliJ). main
  2. By default, your application will start on port 8080.

4. Test Your REST API

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;
    }
}
{
    "message": "Welcome to Spring Boot!"
}

6. Complete!

Congratulations, you’ve successfully created your first REST API with Spring Boot!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.