SendGrid API API in Java

SendGrid API API in Java

This guide shows you how to integrate the SendGrid API into your Java application. Email API for transactional and marketing email with templates and analytics.

Prerequisites

  • Java installed on your system
  • An SendGrid API API key (sign up at https://sendgrid.com)
  • Basic familiarity with HTTP APIs

Installation

<!-- Maven -->
<dependency>
  <groupId>com.squareup.okhttp3</groupId>
  <artifactId>okhttp</artifactId>
  <version>4.12.0</version>
</dependency>

Basic Usage

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class Main {
    private static final String API_KEY = System.getenv().getOrDefault("API_KEY", "YOUR_API_KEY");
    private static final String BASE_URL = "https://api.sendgrid.com";

    public static void main(String[] args) throws Exception {
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(BASE_URL + "/v1/resources"))
            .header("Authorization", "Bearer " + API_KEY)
            .header("Content-Type", "application/json")
            .GET()
            .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println("Status: " + response.statusCode());
        System.out.println(response.body());
    }
}

Error Handling

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 Main {
    private static final String API_KEY = System.getenv().getOrDefault("API_KEY", "YOUR_API_KEY");

    public static String callApiWithRetry(String url, int maxRetries) throws Exception {
        HttpClient client = HttpClient.newBuilder()
            .connectTimeout(Duration.ofSeconds(10))
            .build();

        for (int attempt = 0; attempt < maxRetries; attempt++) {
            try {
                HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(url))
                    .header("Authorization", "Bearer " + API_KEY)
                    .timeout(Duration.ofSeconds(30))
                    .GET()
                    .build();

                HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

                if (response.statusCode() == 429) {
                    System.out.println("Rate limited. Waiting...");
                    Thread.sleep(60000);
                    continue;
                }

                if (response.statusCode() >= 400) {
                    throw new RuntimeException("HTTP " + response.statusCode() + ": " + response.body());
                }

                return response.body();
            } catch (Exception e) {
                System.err.println("Attempt " + (attempt + 1) + " failed: " + e.getMessage());
                if (attempt == maxRetries - 1) throw e;
                Thread.sleep((long) Math.pow(2, attempt) * 1000);
            }
        }
        throw new RuntimeException("Max retries exceeded");
    }

    public static void main(String[] args) throws Exception {
        String result = callApiWithRetry("https://api.sendgrid.com/v1/resources", 3);
        System.out.println(result);
    }
}

Advanced Usage

import com.google.gson.Gson;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.Map;

public class SendgridClient {
    private final String apiKey;
    private final String baseUrl;
    private final HttpClient httpClient;
    private final Gson gson = new Gson();

    public SendgridClient(String apiKey, String baseUrl) {
        this.apiKey = apiKey;
        this.baseUrl = baseUrl.replaceAll("/$", "");
        this.httpClient = HttpClient.newBuilder()
            .connectTimeout(Duration.ofSeconds(10))
            .build();
    }

    public String listResources() throws Exception {
        return request("GET", "/v1/resources", null);
    }

    public String createResource(Map<String, Object> data) throws Exception {
        return request("POST", "/v1/resources", gson.toJson(data));
    }

    private String request(String method, String path, String body) throws Exception {
        HttpRequest.Builder builder = HttpRequest.newBuilder()
            .uri(URI.create(baseUrl + path))
            .header("Authorization", "Bearer " + apiKey)
            .header("Content-Type", "application/json")
            .timeout(Duration.ofSeconds(30));

        if (body != null) {
            builder.method(method, HttpRequest.BodyPublishers.ofString(body));
        } else {
            builder.method(method, HttpRequest.BodyPublishers.noBody());
        }

        HttpResponse<String> response = httpClient.send(builder.build(), HttpResponse.BodyHandlers.ofString());

        if (response.statusCode() >= 400) {
            throw new RuntimeException("API Error: " + response.statusCode() + " - " + response.body());
        }

        return response.body();
    }

    public static void main(String[] args) throws Exception {
        SendgridClient client = new SendgridClient(
            System.getenv("API_KEY"), "https://api.sendgrid.com"
        );
        System.out.println(client.listResources());
    }
}

Best Practices

  • Store your API key in an environment variable, never in source code
  • Implement retry logic with exponential backoff for 429 and 5xx errors
  • Set reasonable timeouts (10-30 seconds) for all API calls
  • Log request IDs from response headers for debugging
  • Cache responses where appropriate to reduce API calls

Other languages