How to Delete Files On-Demand with Java

Learn how to instantly remove files uploaded or generated by calling the pdfRest Delete Files API with Java.
Share this page

Why Delete Files with Java?

The pdfRest Delete Files API Tool is a powerful utility that allows users to delete files stored on the pdfRest platform. This tutorial will guide you through the process of sending an API call to Delete Files using Java. By integrating this API into your Java application, you can programmatically manage and remove files, ensuring that your files are removed promptly after retrieval.

A user might use the Delete Files API to comply with data compliance policies. For instance, if a company processes PDF documents containing private data, they may prefer to proactively delete files as soon as possible rather than waiting for the entire pdfRest file retention period to end.

Delete Files with Java Code Example

import io.github.cdimascio.dotenv.Dotenv;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.*;
import org.json.JSONObject;

public class Delete {

  // By default, we use the US-based API service. This is the primary endpoint for global use.
  private static final String API_URL = "https://api.pdfrest.com";

  // For GDPR compliance and enhanced performance for European users, you can switch to the EU-based
  // service by commenting out the URL above and uncommenting the URL below.
  // For more information visit https://pdfrest.com/pricing#how-do-eu-gdpr-api-calls-work
  // private static final String API_URL = "https://eu-api.pdfrest.com";

  // Specify your API key here, or in the environment variable PDFREST_API_KEY.
  // You can also put the environment variable in a .env file.
  private static final String DEFAULT_API_KEY = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";

  public static void main(String[] args) {

    final Dotenv dotenv = Dotenv.configure().ignoreIfMalformed().ignoreIfMissing().load();

    RequestBody requestBody =
        new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart(
                "ids", "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx")
            .build();
    Request request =
        new Request.Builder()
            .header("Api-Key", dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY))
            .url(API_URL + "/delete")
            .post(requestBody)
            .build();
    try {
      OkHttpClient client =
          new OkHttpClient().newBuilder().readTimeout(60, TimeUnit.SECONDS).build();
      Response response = client.newCall(request).execute();
      System.out.println("Result code " + response.code());
      if (response.body() != null) {
        System.out.println(prettyJson(response.body().string()));
      }
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  private static String prettyJson(String json) {
    // https://stackoverflow.com/a/9583835/11996393
    return new JSONObject(json).toString(4);
  }
}

Source: GitHub Repository

Breaking Down the Code

The code begins by importing necessary libraries, such as io.github.cdimascio.dotenv.Dotenv for environment variable management, okhttp3.* for HTTP requests, and org.json.JSONObject for JSON handling.

private static final String API_URL = "https://api.pdfrest.com";

This line sets the API endpoint to the US-based service. There's an option to switch to the EU-based service for GDPR compliance by uncommenting the relevant line.

private static final String DEFAULT_API_KEY = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";

The API key is specified here, which can also be set in an environment variable or a .env file. This key is essential for authenticating requests.

RequestBody requestBody = new MultipartBody.Builder()
    .setType(MultipartBody.FORM)
    .addFormDataPart("ids", "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx")
    .build();

This snippet constructs the request body. The ids parameter contains the file IDs to be deleted, separated by commas. Each ID represents a file stored on the pdfRest platform.

Request request = new Request.Builder()
    .header("Api-Key", dotenv.get("PDFREST_API_KEY", DEFAULT_API_KEY))
    .url(API_URL + "/delete")
    .post(requestBody)
    .build();

A Request object is created, specifying the API key in the header and setting the URL to the /delete endpoint. The request body is attached using the POST method.

OkHttpClient client = new OkHttpClient().newBuilder().readTimeout(60, TimeUnit.SECONDS).build();
Response response = client.newCall(request).execute();

An OkHttpClient is instantiated with a 60-second read timeout. The execute() method sends the request and receives a Response.

Beyond the Tutorial

In this tutorial, you learned how to use Java to send a request to the pdfRest Delete Files API, allowing you to programmatically manage files on the platform. To further explore the capabilities of pdfRest, try out all the API Tools in the API Lab. For more detailed information, consult the API Reference Guide.

Note: This is an example of a multipart API call. Code samples using JSON payloads can be found at GitHub Repository.

Generate a self-service API Key now!
Create your FREE API Key to start processing PDFs in seconds, only possible with pdfRest.