Spring Boot for Beginners: Creating Your First REST API

 Spring Boot is a powerful Java framework that simplifies backend development. In this guide, we will create a basic REST API using Spring Boot, covering everything from setting up the project to testing the API endpoints.

 


Prerequisites

Before we begin, ensure you have the following installed:

  • Java Development Kit (JDK) 17 or later

  • Spring Boot (via Spring Initializr)

  • An Integrated Development Environment (IDE) like IntelliJ IDEA or Eclipse

  • Postman or cURL for API testing

 

Step 1: Setting Up a Spring Boot Project

  1. Go to Spring Initializr.

  2. Select the following options:

    • Project: Maven

    • Language: Java

    • Spring Boot Version: Latest stable release

    • Dependencies: Spring Web

  3. Click Generate to download the project.

  4. Extract the ZIP file and open it in your IDE.

Step 2: Creating the REST Controller

Inside the src/main/java/com/example/demo directory, create a new class named HelloController.java.

package com.example.demo.controller;

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 HelloController {

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

Step 3: Running the Application

Run the application using the following command:

http://localhost:8080/api/hello

You should see the response:

Hello, Spring Boot!

 

Conclusion

Congratulations! You have successfully created your first REST API using Spring Boot. From here, you can explore more features such as request parameters, database integration, and security.

Next Steps:

  • Implement CRUD operations

  • Integrate with a database using Spring Data JPA

  • Secure the API using JWT authentication

If you found this guide helpful, share it with others and subscribe for more tutorials on Spring Boot and Java development!