Build a Simple “Hello World” API
Spring Boot makes it easy to create REST APIs with minimal configuration. This guide walks you through building a simple Hello World API.
Step 1: Create a Spring Boot Project
Use Spring Initializr to generate a project:
- Project: Maven or Gradle
- Language: Java
- Spring Boot Version: Latest stable (e.g., 3.x)
- Dependencies: Spring Web
Download the project and open it in your IDE (IntelliJ IDEA, Eclipse, or VS Code).
Project Structure:
src/main/java/com/example/demo
└── DemoApplication.java
src/main/resources
└── application.properties
Step 2: Create the Main Application Class
The main class is annotated with @SpringBootApplication and serves as the entry point:
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);
}
}
Step 3: Create a REST Controller
Controllers handle HTTP requests. Create HelloController.java:
package com.example.demo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "Hello World!";
}
}
- @RestController: Combines
@Controller+@ResponseBody. - @GetMapping("/hello"): Maps HTTP GET requests to
/hello.
Step 4: Run the Application
You can run your Spring Boot app in multiple ways:
1. From IDE: Right-click DemoApplication → Run/Debug.
2. Using Maven:
mvn spring-boot:run
3. Using Gradle:
./gradlew bootRun
4. Running the JAR:
java -jar target/demo-0.0.1-SNAPSHOT.jar
By default, Spring Boot starts an embedded Tomcat server on port 8080.
Step 5: Test the API
Open your browser or Postman and navigate to:
<http://localhost:8080/hello>
Response:
Hello World!
Step 6: Optional Enhancements
Change Server Port (application.properties):
server.port=8081
Enable Logging (application.properties):
logging.level.com.example.demo=DEBUG
Use Profiles (dev/test/prod):
spring.profiles.active=dev
Conclusion
You now have a fully working “Hello World” REST API with Spring Boot.
Key Points:
- No XML configuration required.
- Embedded server starts automatically.
- Controllers map HTTP requests easily.
- Can be extended with services, repositories, and database integration.
- Serves as a foundation for RESTful APIs and microservices.
