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:

  1. Imports necessary classes: `java.net.URI`, `java.net.http.HttpClient`, `java.net.http.HttpRequest`, `java.net.http.HttpResponse`, and `com.google.gson.Gson`. We use Gson to parse the json response.
  2. Creates an `HttpClient` instance: `HttpClient.newHttpClient()` creates a default HTTP client.
  3. Builds an `HttpRequest`: `HttpRequest.newBuilder()` starts building a request to the specified URL. We set the URI using `URI.create(url)`.
  4. Sends the request: `client.send(request, HttpResponse.BodyHandlers.ofString())` sends the GET request and retrieves the response body as a string.
  5. Prints the status code and response body: This allows you to inspect the raw response from the server.
  6. Parses the JSON response: It uses Gson library to convert the JSON string into a Java object (Post). Make sure to add Gson as a dependency in your project (e.g., using Maven or Gradle).
  7. Prints the parsed data: Demonstrates accessing the fields from the parsed Java object.

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:

  • HTTP Client: The `HttpClient` is used to make HTTP requests.
  • HTTP Request: The `HttpRequest` represents the HTTP request to be sent. You can customize it with headers, methods (GET, POST, PUT, DELETE), and request bodies.
  • HTTP Response: The `HttpResponse` represents the server's response to the request. It includes status codes, headers, and the response body.
  • REST API: A REST API is an architectural style for building web services that uses HTTP methods to access and manipulate resources identified by URIs.
  • JSON: JavaScript Object Notation is a lightweight data-interchange format. REST APIs often return data in JSON format.
  • JSON Parsing: Libraries like Gson are used to convert JSON strings into Java objects and vice versa.

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

  • Error Handling: Wrap the `client.send()` call in a `try-catch` block to handle potential `IOExceptions` or `InterruptedExceptions`.
  • Status Code Handling: Check the `response.statusCode()` to ensure the request was successful (e.g., 200 OK). Handle different status codes appropriately (e.g., 404 Not Found, 500 Internal Server Error).
  • Asynchronous Requests: For non-blocking I/O, use the `HttpClient.sendAsync()` method to send requests asynchronously.
  • Connection Pooling: The `HttpClient` automatically handles connection pooling, improving performance.
  • Data Validation: Validate the data received from the API to ensure it is in the expected format and range.

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

  • Apache HttpClient: A widely used library for making HTTP requests in Java (older alternative, still used).
  • OkHttp: Another popular HTTP client library known for its performance and reliability.
  • Spring's RestTemplate/WebClient: Part of the Spring Framework, offering a higher-level abstraction for consuming REST APIs. WebClient is the reactive, non-blocking alternative.

Pros

  • Simple and standardized: REST uses standard HTTP methods and is easy to understand.
  • Lightweight: JSON is a lightweight data format.
  • Scalable: REST APIs can be easily scaled to handle large numbers of requests.
  • Widely adopted: Many APIs are built using REST.

Cons

  • Over-fetching/Under-fetching: REST APIs might return more or less data than needed.
  • Multiple round trips: Sometimes, you might need to make multiple requests to get all the required data.
  • Lack of standardization: While REST is an architectural style, the specific implementation can vary between APIs.

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: xml com.google.code.gson gson 2.8.9 If you are using Gradle, add the following to your `build.gradle` file: gradle dependencies { implementation 'com.google.code.gson:gson:2.8.9' // Use the latest version }
  • 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();