Spring Boot RESTful Web Services
๐ฑ What is Spring Boot?
Spring Boot is a tool in Java that helps you build web apps and APIs quickly. It removes a lot of boring setup and lets you just focus on writing your logic.
---
๐ What are RESTful Web Services?
RESTful Web Services allow computers to talk to each other over the internet using HTTP (like your browser does).
Imagine this:
๐ง๐ณ You ask a restaurant (a server) for a menu item (a resource), like /burger.
The restaurant gives it to you in a standard way (usually JSON format).
That’s a RESTful service!
---
๐ค Why Use Spring Boot for REST?
✅ Quick to set up
✅ Less code needed
✅ Easy to test and run
✅ Comes with tools like an embedded server (Tomcat)
---
๐ฆ Example: Let's Create a Simple REST API
Let’s say we want to create a REST API for a "Hello World" service.
๐งฑ Step-by-Step
1. ✅ Create a Spring Boot Project
You can use https://start.spring.io
Choose Spring Web dependency
Click "Generate" and unzip the project
2. ✍️ Create a Controller (The heart of the REST API)
package com.example.demo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController // This makes it a REST API
public class HelloController {
@GetMapping("/hello") // This maps to the URL: http://localhost:8080/hello
public String sayHello() {
return "Hello, World!";
}
}
3. ๐ Run the Application
Run the project like a normal Java app (using the main method):
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);
}
}
4. ๐ Try It Out
Open your browser and go to:
http://localhost:8080/hello
You’ll see:
Hello, World!
๐ That’s your first RESTful service!
---
๐ง What's Happening Behind the Scenes?
---
๐งช Bonus: Return JSON instead of plain text
@GetMapping("/greet")
public Map<String, String> greet() {
return Map.of("message", "Hello, JSON!");
}
๐ Visit /greet and you get:
{
"message": "Hello, JSON!"
}
Comments
Post a Comment