REST APIs
suggest changeA REST (Representational State Transfer) API is an architectural style for networked applications that uses HTTP methods to perform CRUD operations on resources, typically exchanging data in JSON format.
In modern Java, you can both consume external REST services and build full-featured RESTful servers using built-in JDK tools or industry-standard frameworks like Spring Boot and Jakarta REST (JAX-RS).
1. Consuming REST APIs with java.net.http.HttpClient
Introduced in Java 11, java.net.http.HttpClient is the modern, standard HTTP client in the JDK. It supports both synchronous and asynchronous requests, HTTP/2, and reactive streams.
Synchronous GET Request
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
public class RestClientExample {
public static void main(String[] args) throws IOException, InterruptedException {
HttpClient client = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_2)
.connectTimeout(Duration.ofSeconds(10))
.build();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://jsonplaceholder.typicode.com/posts/1"))
.header("Accept", "application/json")
.GET()
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("Status Code: " + response.statusCode());
System.out.println("Headers: " + response.headers().map());
System.out.println("Response Body:\n" + response.body());
}
}
POST Request with JSON Payload
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class RestPostExample {
public static void main(String[] args) throws Exception {
HttpClient client = HttpClient.newHttpClient();
String jsonPayload = """
{
"title": "foo",
"body": "bar",
"userId": 1
}
""";
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://jsonplaceholder.typicode.com/posts"))
.header("Content-Type", "application/json; charset=UTF-8")
.header("Accept", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(jsonPayload))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() == 201) {
System.out.println("Created successfully: " + response.body());
} else {
System.err.println("Request failed with status: " + response.statusCode());
}
}
}
Asynchronous API Call with CompletableFuture
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.concurrent.CompletableFuture;
public class AsyncRestClient {
public static void main(String[] args) {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://jsonplaceholder.typicode.com/users/1"))
.GET()
.build();
CompletableFuture<HttpResponse<String>> future = client.sendAsync(
request,
HttpResponse.BodyHandlers.ofString()
);
future.thenApply(HttpResponse::body)
.thenAccept(System.out::println)
.join(); // Wait for completion in demonstration
}
}
2. Parsing JSON Responses with Modern Records and Jackson
In enterprise Java, JSON serialization and deserialization is typically handled with libraries like Jackson or Gson. Combined with Java record types, mapping DTOs is concise and immutable:
import com.fasterxml.jackson.databind.ObjectMapper;
// Java 16+ record for immutable DTO
public record User(int id, String name, String email) {}
class JsonMappingExample {
private static final ObjectMapper mapper = new ObjectMapper();
public static void main(String[] args) throws Exception {
String json = "{\"id\": 1, \"name\": \"Alice\", \"email\": \"alice@example.com\"}";
// Deserialize JSON to Java record
User user = mapper.readValue(json, User.class);
System.out.println("Parsed user: " + user.name() + " (" + user.email() + ")");
// Serialize Java record back to JSON
String serialized = mapper.writeValueAsString(user);
System.out.println("Serialized JSON: " + serialized);
}
}
3. Creating a Zero-Dependency REST API with HttpServer
For simple microservices or test mocks without external dependencies, Java includes com.sun.net.httpserver.HttpServer:
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
public class MinimalRestServer {
public static void main(String[] args) throws IOException {
HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
server.createContext("/api/health", new HttpHandler() {
@Override
public void handle(HttpExchange exchange) throws IOException {
if ("GET".equalsIgnoreCase(exchange.getRequestMethod())) {
String jsonResponse = "{\"status\":\"UP\",\"timestamp\":" + System.currentTimeMillis() + "}";
byte[] bytes = jsonResponse.getBytes(StandardCharsets.UTF_8);
exchange.getResponseHeaders().set("Content-Type", "application/json");
exchange.sendResponseHeaders(200, bytes.length);
try (OutputStream os = exchange.getResponseBody()) {
os.write(bytes);
}
} else {
exchange.sendResponseHeaders(405, -1); // Method Not Allowed
}
}
});
server.setExecutor(null); // Default single-thread executor
System.out.println("Server running on http://localhost:8080/api/health");
server.start();
}
}
4. Building REST APIs with Spring Boot
In industry applications, Spring Boot is the most widely adopted framework for building production-grade REST APIs.
Controller Example
package com.example.demo.controller;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
@RestController
@RequestMapping("/api/products")
public class ProductController {
public record Product(Long id, String name, double price) {}
public record CreateProductRequest(String name, double price) {}
private final Map<Long, Product> database = new ConcurrentHashMap<>();
private final AtomicLong idGenerator = new AtomicLong(1);
// GET /api/products
@GetMapping
public List<Product> getAllProducts() {
return new ArrayList<>(database.values());
}
// GET /api/products/{id}
@GetMapping("/{id}")
public ResponseEntity<Product> getProductById(@PathVariable Long id) {
Product product = database.get(id);
if (product == null) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok(product);
}
// POST /api/products
@PostMapping
public ResponseEntity<Product> createProduct(@RequestBody CreateProductRequest req) {
long newId = idGenerator.getAndIncrement();
Product product = new Product(newId, req.name(), req.price());
database.put(newId, product);
return ResponseEntity.status(HttpStatus.CREATED).body(product);
}
// DELETE /api/products/{id}
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteProduct(@PathVariable Long id) {
if (database.remove(id) == null) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.noContent().build();
}
}
5. Building REST APIs with Jakarta RESTful Web Services (JAX-RS)
JAX-RS (Jakarta EE / Quarkus / Jersey) is the standard Java specification for RESTful services:
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
@Path("/items")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class ItemResource {
@GET
@Path("/{id}")
public Response getItemById(@PathParam("id") String id) {
if ("404".equals(id)) {
return Response.status(Response.Status.NOT_FOUND).build();
}
return Response.ok("{\"id\":\"" + id + "\",\"name\":\"Widget\"}").build();
}
@POST
public Response createItem(String jsonPayload) {
// Persist item...
return Response.status(Response.Status.CREATED)
.entity(jsonPayload)
.build();
}
}
6. Best Practices
- Use Proper HTTP Methods:
GET: Read operations (safe and idempotent).POST: Create new resources (non-idempotent).PUT: Complete resource replacement (idempotent).PATCH: Partial updates.DELETE: Remove resource (idempotent).
- Return Meaningful HTTP Status Codes:
200 OK,201 Created,204 No Content,400 Bad Request,401 Unauthorized,403 Forbidden,404 Not Found, and500 Internal Server Error. - Set Timeouts: Always configure connection and read timeouts on
HttpClientto prevent hanging thread resources. - Statelessness: Avoid holding client session state on the server. Prefer token-based authentication (such as JWTs or OAuth2 bearer tokens) passed in the
Authorizationheader.