First REST API
REST Concepts
REST (Representational State Transfer) is an architecture for HTTP-based APIs. Every resource is identified by a URI and operated on using HTTP methods.
| HTTP Method | Operation | Example URI | Description |
|---|---|---|---|
GET |
Read | /api/users |
Fetch data |
POST |
Create | /api/users |
Create new data |
PUT |
Update | /api/users/1 |
Update data |
PATCH |
Partial Update | /api/users/1 |
Update some fields |
DELETE |
Delete | /api/users/1 |
Delete data |
@RestController
An annotation that marks a class as a REST controller. The return value is automatically converted to JSON by Jackson.
@RestController
@RequestMapping("/api/users")
public class UserController {
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping
public List<User> getAll() {
return userService.findAll();
}
}
@GetMapping
A shortcut annotation for @RequestMapping(method = RequestMethod.GET):
// Option 1: with @GetMapping
@GetMapping("/{id}")
public User getById(@PathVariable Long id) {
return userService.findById(id);
}
// Option 2: with @RequestMapping
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public User getById(@PathVariable Long id) {
return userService.findById(id);
}
Both options produce the same endpoint. @GetMapping is shorter and more readable.
@RequestMapping
Can be used at the class level as a path prefix:
@RestController
@RequestMapping("/api/v1") // All endpoints are prefixed with /api/v1
public class UserController {
@GetMapping("/users") // → GET /api/v1/users
@PostMapping("/users") // → POST /api/v1/users
@GetMapping("/users/{id}") // → GET /api/v1/users/1
}
Model: User.java
public class User {
private Long id;
private String name;
private String email;
public User() {}
public User(Long id, String name, String email) {
this.id = id;
this.name = name;
this.email = email;
}
// getters & setters
}
Complete: UserController
@RestController
@RequestMapping("/api/users")
public class UserController {
private final List<User> users = List.of(
new User(1L, "John", "[email protected]"),
new User(2L, "Sarah", "[email protected]")
);
@GetMapping
public List<User> getAll() {
return users;
}
@GetMapping("/{id}")
public User getById(@PathVariable Long id) {
return users.stream()
.filter(u -> u.getId().equals(id))
.findFirst()
.orElseThrow(() -> new RuntimeException("User not found"));
}
@GetMapping("/search")
public List<User> search(@RequestParam String name) {
return users.stream()
.filter(u -> u.getName().contains(name))
.toList();
}
}
Testing in a Browser
GET http://localhost:8080/api/users
JSON response:
[
{"id":1, "name":"John", "email":"[email protected]"},
{"id":2, "name":"Sarah", "email":"[email protected]"}
]
Testing with Postman
- Open Postman (or Thunder Client in VS Code)
- Set the method:
GET - URL:
http://localhost:8080/api/users - Click Send
The response is automatically in JSON format.
Automatic JSON Response (Jackson)
Spring Boot uses Jackson to convert Java objects to JSON. When a method returns a User, Jackson automatically serializes it to JSON.
Jackson uses getter methods to determine which fields to include:
// Only the "name" field appears in the JSON
public class User {
private Long id;
@JsonIgnore
private String password; // Not included in the JSON
public String getName() { return name; }
}
| Jackson Annotation | Purpose |
|---|---|
@JsonIgnore |
Hide a field from the JSON |
@JsonProperty("full_name") |
Rename a field in the JSON |
@JsonFormat(pattern="yyyy-MM-dd") |
Format dates |
Summary
| Concept | Annotation |
|---|---|
| REST Controller | @RestController |
| Base Path | @RequestMapping |
| GET Endpoint | @GetMapping |
| URL Parameter | @PathVariable |
| Query Parameter | @RequestParam |
| JSON Serialization | Jackson (automatic) |
You've now gone from the basics of Spring to building your first REST API. From here, you can explore advanced topics such as Spring Data JPA for databases, Spring Security for authentication, and Spring Cloud for microservices.