Call REST API endpoints from Java using HttpClient

Table of contents

Normally, we use languages like Java, C# to implement the API. There are some scenarios where we are also required to call third party APIs or other external APIs from our backend service implemented in such language.

Java has handy library HttpClient which can call HTTP requests. e.g. if I have an external weather API that gives me an array of weather data as below:

[
  {
    "date": "2024-03-17",
    "temperatureC": -11,
    "temperatureF": 13,
    "summary": "Freezing"
  },
  {
    "date": "2024-03-18",
    "temperatureC": 50,
    "temperatureF": 121,
    "summary": "Sweltering"
  },
  {
    "date": "2024-03-19",
    "temperatureC": -18,
    "temperatureF": 0,
    "summary": "Hot"
  },
  {
    "date": "2024-03-20",
    "temperatureC": 6,
    "temperatureF": 42,
    "summary": "Mild"
  },
  {
    "date": "2024-03-21",
    "temperatureC": 14,
    "temperatureF": 57,
    "summary": "Balmy"
  }
]

I could use HttpClient in Java to Get this data like below.

HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .method("GET", HttpRequest.BodyPublishers.noBody())
                .build();
        HttpResponse<String> response = null;
        try {
            response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
        } catch (Exception ex) {
            ...
        }

Further we can create Temperature object and Deserialize incoming JSON coming from above call using Jackson Object Mapper.

var mapper = new ObjectMapper();
//Deserialize.
Tempratures[] tempratures = mapper.readValue(response.body(), Tempratures[].class);

HTTP POST with HTTPClient

Just like GET we could utilize HttpClient to perform POST request like below.

Tempratures temprature = new Tempratures();
temprature.setSummary("Hot");
temprature.setDate(new Date());

HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .POST(HttpRequest.BodyPublishers.ofString(temprature.toString()))
                .build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());