Making API Calls in Java: A Comprehensive Guide

Introduction to API Calls

API (Application Programming Interface) calls are a fundamental part of modern software development. They allow applications to communicate with each other, typically over the web. In Java, making an API call involves sending an HTTP request to a server and receiving a response.

Understanding HTTP Methods

  1. GET: Retrieves data from a server. It should not have side effects (like changing data).
  2. POST: Sends data to the server, often used for creating resources.
  3. PUT: Updates an existing resource on the server.
  4. DELETE: Deletes a resource on the server.
  5. PATCH: Partially updates a resource on the server.

When to Use Which Method

  • Use GET for fetching data.
  • Use POST when submitting data to be processed to a server.
  • Use PUT and PATCH for updating resources, with PUT for complete updates and PATCH for partial updates.
  • Use DELETE to remove data from the server.

Request, Request Body, and Response

  • Request: An HTTP request includes a method (like GET or POST), a URL, headers, and sometimes a request body.
  • Request Body: The data sent to the server, typically with POST or PUT requests. It’s often formatted as JSON or XML.
  • Response: The data returned by the server, usually also in a standardized format like JSON or XML.

Example: Making a POST Request with a Request Body

Let’s say we want to create a new user on a server by making a POST request with user details.

Code Example:

import java.net.HttpURLConnection;
import java.net.URL;
import java.io.OutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class PostRequestExample {
    public static void main(String[] args) {
        String apiUrl = "https://api.example.com/users";
        String jsonInputString = "{\"name\": \"John\", \"age\": 30}";

        try {
            URL url = new URL(apiUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json; utf-8");
            connection.setRequestProperty("Accept", "application/json");
            connection.setDoOutput(true);

            try(OutputStream os = connection.getOutputStream()) {
                byte[] input = jsonInputString.getBytes("utf-8");
                os.write(input, 0, input.length);           
            }

            try(BufferedReader br = new BufferedReader(
                new InputStreamReader(connection.getInputStream(), "utf-8"))) {
                StringBuilder response = new StringBuilder();
                String responseLine;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine.trim());
                }
                System.out.println(response.toString());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Explanation:

  • The URL of the API and the JSON input string (request body) are defined.
  • A HttpURLConnection object is created to open a connection to the API.
  • The request method is set to “POST”, and headers are set to indicate the content type.
  • The request body (JSON data) is written to the output stream of the connection.
  • The response from the server is read and printed.

Transforming the Response into a Java Bean

Let’s say the server responds with user data in JSON format. We can transform this JSON response into a Java Bean for easy manipulation.

Java Bean Example:

public class User {
    private String name;
    private int age;

    // Getters and Setters
}

Converting JSON to Java Bean:

You can use a library like Jackson or Gson to convert the JSON response to a User object:

User user = new ObjectMapper().readValue(response.toString(), User.class);

Conclusion

Making API calls in Java is a crucial skill in today’s interconnected software environment. Understanding when to use different HTTP methods, how to send requests with bodies, and how to handle responses are key components of this skill. Transforming API responses into Java Beans further simplifies data manipulation, making it a valuable technique for developers.