Table of Contents
Spring Boot Getting Started Guide: Build Your First REST API with Java
Spring Boot is a popular framework for building robust and scalable REST APIs with Java. This guide will walk you through creating your first REST API using Spring Boot, perfect for beginners and experienced developers alike.
Prerequisites
- Java Development Kit (JDK) 11 or higher
- Integrated Development Environment (IDE) such as IntelliJ IDEA or Eclipse
- Basic knowledge of Java programming
- Internet connection to download dependencies
Setting Up Your Spring Boot Project
You can quickly start a new Spring Boot project using Spring Initializr. Visit start.spring.io and configure your project with the following options:
- Project: Maven Project
- Language: Java
- Spring Boot version: Latest stable release
- Project Metadata: Fill as desired
- Dependencies: Spring Web
Click "Generate" to download a ZIP file. Extract it to your workspace and open it in your IDE.
Creating the REST Controller
Navigate to src/main/java/com/example/demo and create a new Java class named GreetingController. Add the following code:
package com.example.demo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class GreetingController {
@GetMapping("/api/greeting")
public String getGreeting() {
return "Hello, World!";
}
}
Running Your Application
Open your main application class DemoApplication.java and ensure it contains the @SpringBootApplication annotation. Then, run the application:
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
Once the application starts, open your browser and navigate to http://localhost:8080/api/greeting. You should see the message Hello, World!.
Next Steps
From here, you can extend your API by adding more endpoints, connecting to databases, and implementing business logic. Spring Boot provides a comprehensive framework for building production-ready REST APIs efficiently.
Summary
This guide covered the basics of setting up a Spring Boot project, creating a simple REST API, and running your application. With these foundations, you're ready to explore more advanced features and build complex APIs with Java and Spring Boot.