Java > Java Networking > HTTP and Web Services > SOAP vs REST APIs
Java HTTP Client Example: REST API Consumption
This snippet demonstrates how to consume a REST API using Java's `java.net.http` package (introduced in Java 11). It showcases making a GET request and parsing the JSON response.
Code Snippet
This code performs the following steps:
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import com.google.gson.Gson;
//Record to represent a Post from the API (using Gson)
record Post(int userId, int id, String title, String body){}
public class RestClientExample {
public static void main(String[] args) throws Exception {
String url = "https://jsonplaceholder.typicode.com/posts/1";
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("Status Code: " + response.statusCode());
System.out.println("Response Body: " + response.body());
// Parse JSON response
Gson gson = new Gson();
Post post = gson.fromJson(response.body(), Post.class);
System.out.println("Parsed Post Title: " + post.title());
System.out.println("Parsed Post Body: " + post.body());
}
}
Concepts Behind the Snippet
This snippet illustrates key concepts in REST API consumption:
Real-Life Use Case
Imagine you are building a weather application. You can use this code (with necessary adjustments to the URL and data parsing) to fetch weather data from a weather API (e.g., OpenWeatherMap) and display it to the user. Other use cases include fetching data from social media APIs (Twitter, Facebook), retrieving product information from an e-commerce API, or integrating with any other service that provides a REST API.
Best Practices
Interview Tip
When discussing REST API consumption in Java, be prepared to explain the role of `HttpClient`, `HttpRequest`, and `HttpResponse`. Also, be ready to discuss different HTTP methods (GET, POST, PUT, DELETE) and their use cases. Knowing about JSON parsing libraries like Gson or Jackson is also helpful.
When to use them
REST APIs are suitable for scenarios where you need to access and manipulate resources over the internet using a simple and standardized interface. They are well-suited for web applications, mobile apps, and integrations between different systems.
Alternatives
Pros
Cons
FAQ
-
What is Gson and why is it used?
Gson is a Java library for serializing and deserializing Java objects to and from JSON. In this snippet, it's used to parse the JSON response from the API into a `Post` object, making it easier to access the data. -
How do I add Gson to my project?
If you are using Maven, add the following dependency to your `pom.xml` file: xmlcom.google.code.gson gson 2.8.9 -
What if the API requires authentication?
You would need to add authentication headers to the `HttpRequest`. The specific headers required depend on the API's authentication scheme (e.g., API key, OAuth 2.0). For example, to add an API key: java HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(url)) .header("X-API-Key", "YOUR_API_KEY") .build();