Building REST APIs with Spring Boot | Spring Web MVC
REST APIs are the foundation of modern web and mobile applications. They enable services to communicate across platforms using simple HTTP protocols. Spring Boot makes creating RESTful services straightforward, offering a combination of powerful features like annotation-driven endpoints, JSON serialization with Jackson, and seamless integration with tools like Postman for testing.
This guide covers building and testing REST APIs with Spring Boot, including GET and POST endpoints, handling request data with annotations, JSON serialization and deserialization using Jackson, and tips for using Postman to ensure your APIs function correctly.
Table of Contents
- Creating Simple GET/POST Endpoints
- Using
@RequestBody
,@PathVariable
, andResponseEntity
- JSON Serialization with Jackson
- Testing APIs with Postman
- External Resources for Further Learning
- Final Thoughts
Creating Simple GET/POST Endpoints
What Are Endpoints?
REST APIs are composed of endpoints, which are URLs that clients can access to send requests. Typically, these are categorized under HTTP methods like:
- GET – Retrieve information.
- POST – Submit data to the server.
- PUT – Update existing information.
- DELETE – Remove information.
Spring Boot REST Controller
A REST controller in Spring Boot is annotated with @RestController
, which simplifies responses by automatically serializing objects into JSON.
Example GET Endpoint
HelloController.java:
package com.example.demo.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/hello")
public String sayHello() {
return "Hello, World!";
}
}
@GetMapping
maps HTTP GET requests to thesayHello()
method.- Launch the application and visit
http://localhost:8080/hello
to see the response.
Example POST Endpoint
PostController.java:
package com.example.demo.controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class PostController {
@PostMapping("/submit")
public String handleSubmit(@RequestBody String data) {
return "Data received: " + data;
}
}
@PostMapping
maps HTTP POST requests tohandleSubmit()
.- The
@RequestBody
annotation binds the JSON payload in the request body to thedata
parameter.
Using @RequestBody
, @PathVariable
, and ResponseEntity
1. @RequestBody
Used to map the payload of an HTTP request to a Java object. This is essential for endpoints handling POST/PUT requests.
Example:
@PostMapping("/users")
public String createUser(@RequestBody User user) {
return "User created with name: " + user.getName();
}
If the JSON payload is:
{
"name": "John",
"email": "john.doe@example.com"
}
It will be mapped to the User
object.
2. @PathVariable
Used to extract values from the URL path.
Example:
UserController.java:
@GetMapping("/users/{id}")
public String getUser(@PathVariable int id) {
return "Fetching user with ID " + id;
}
Accessing http://localhost:8080/users/5
would bind 5
to the id
variable.
3. ResponseEntity
Provides more control over HTTP responses, including headers, status codes, and body content.
Example:
@GetMapping("/status")
public ResponseEntity<String> getStatus() {
return ResponseEntity.ok()
.header("Custom-Header", "example")
.body("Application is running!");
}
The above response will include:
- 200 OK status code.
- Custom
Custom-Header
. - Body content “Application is running!”.
JSON Serialization with Jackson
Jackson is a built-in library in Spring Boot for serializing (converting Java objects to JSON) and deserializing (converting JSON to Java objects).
Example Entity
User.java:
package com.example.demo.model;
public class User {
private String name;
private String email;
// Getters and Setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Serialization Example
The following GET
endpoint returns a User
object, which Jackson converts to JSON.
UserController.java:
@GetMapping("/user")
public User getUser() {
User user = new User();
user.setName("Alice");
user.setEmail("alice@example.com");
return user;
}
Response JSON:
{
"name": "Alice",
"email": "alice@example.com"
}
Customizing JSON with Annotations
Jackson also supports annotations like @JsonIgnore
and @JsonProperty
to control how objects are serialized.
Example:
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
public class User {
@JsonProperty("full_name")
private String name;
@JsonIgnore
private String password;
// Getters and Setters
}
@JsonProperty("full_name")
: Maps thename
field tofull_name
in JSON.@JsonIgnore
: Excludespassword
from the JSON output.
Testing APIs with Postman
Postman is a popular tool for testing REST APIs. It allows developers to send HTTP requests, view responses, set headers, and automate testing processes.
Steps to Test REST APIs
- Install Postman
Download Postman from the official website. - Testing a GET Endpoint
- Open Postman and create a new GET request.
- Enter the URL
http://localhost:8080/hello
. - Click Send and verify the response is “Hello, World!”.
- Testing a POST Endpoint
- Switch to a POST request.
- Enter the URL
http://localhost:8080/users
. - Under Body, select raw, choose
JSON
, and add the payload:{ "name": "John", "email": "john.doe@example.com" }
- Click Send and verify the response.
- Using Collections
Group related API requests into collections for better organization and automated testing workflows.
External Resources for Further Learning
Final Thoughts
REST APIs are the backbone of modern applications, and Spring Boot provides an intuitive framework for building them efficiently. Whether you’re working on simple endpoints or enterprise-grade integrations, tools like Spring Boot and Jackson simplify development, leaving you to focus on delivering functionality. Tools like Postman further enhance the development experience, enabling you to test your APIs seamlessly.
With this guide, you’ve learned how to create, handle, and test REST APIs in Spring Boot using best practices and industry-standard tools. Bookmark this guide and start building your RESTful services today!