Skip to content

Calling Plumber APIs from Java#

Requirements#

To call APIs hosted in RStudio Connect from Java, you'll need:

  1. URL for the API endpoint hosted on RStudio Connect
  2. API key (if your API requires authorization)

Java example#

You can use the url.openConnection method in Java to call Plumber APIs from Java applications:

import java.io.*;
import java.net.*;

public class RestApi {

    public static void main(String[] args) throws IOException {

        String CONNECT_API_URL = "https://connect.yourcompany.com/rest-api-example/endpoint";
        String CONNECT_API_KEY = "YfB5XBRB7slkkBSEi5qr93mWJvbpXQQy";

        URL url = new URL(CONNECT_API_URL);
        URLConnection urlc = url.openConnection();
        urlc.setRequestProperty("Authorization", "Key " + CONNECT_API_KEY);

        BufferedReader br = new BufferedReader(new InputStreamReader(urlc.getInputStream()));
        String l = null;
        while ((l=br.readLine())!=null) {
            System.out.println(l);
        }
        br.close();
    }
}

You can replace the values of CONNNECT_API_URL and CONNECT_API_KEY with your API URL and API key from RStudio Connect.

Scope#

The code examples assume that you are calling a published API in RStudio Connect that is:

  • Hosted on a secure server with TLS/SSL at an HTTPS endpoint
  • Using an API key to make an authorized call to an API
  • Making an HTTP GET request to the API

If your use case is different, then you can modify the example code accordingly.