Content APIs (Java)

Learn how to call unauthenticated and authenticated APIs.

This getting started tutorial walks you through a simple scenario to retrieve a content item by ID from the delivery content service and the authoring content service. You'll learn how to call unauthenticated and authenticated APIs. By the end of the tutorial, you can make your own calls and retrieve responses from the Content APIs.

Before you begin

Get familiar with the Content APIs

  • Content offers you REST-based APIs to create, manage, and deliver your content. For example, use the authoring services API to create and manage content and the delivery services API to integrate content into your applications.
  • The format of the Content REST API URLs is {API URL}/{ API endpoint}.
    The API URL is constructed as Domain name/{path} where {path}= api/{Content ID}.
    The API endpoints are described in the Content API documentation. For example, use endpoint /delivery/v1/content/{Item ID} or endpoint /authoring/v1/content/{Item ID} to access content items.
  • Most of the APIs require you to authenticate through the /login/v1/basicauth endpoint before you can access them except for delivery APIs, which are available to anonymous, unauthenticated callers.

Example: To retrieve a published content item by ID

  1. Get the Item ID from the Content user interface. Open the specific content item that you want and click the API information icon.
    ItemId = "b7abe31d-7763-41a9-b8d5-f7cf78565cbd"
  2. Provide the Item ID in the delivery API: {APIURL}/delivery/v1/content/{Item ID}.
    https://content-XX-N.content-cms.com/api/12345678-...-56789abcdef0/delivery/v1/content/'b7abe31d-7763-41a9-b8d5-f7cf78565cbd

Get the API URL for your subscription

You can get your API URL from the Content Authoring UI.
Click Developer > URL information. Your API URL would look similar to API URL - https://{Domain name}/api/{ContentID}
For example, https://content-XX-N.content-cms.com/api/12345678-9abc-def0-1234-56789abcdef0.

Make HTTP REST requests from Java

This tutorial uses the classes available with J2SE Java 1.8 SDK to make the API calls. The primary classes you would use for making HTTP REST requests from Java include the following, along with other required imports for streams and exceptions.

import java.net.HttpURLConnection; 
import java.net.CookieHandler;  
import java.net.CookieManager;  
import java.net.CookiePolicy;  
import java.net.URL; 
import java.util.Base64;

Define the constants

Define the constants for the Content API URL, Content API endpoints, content ID, and the username to authenticate.

// Acoustic Content tenant specific API URL, of the form https://{tenant-host}/api/{tenant-id} 
    static String myTenantBaseAPIURL = "https://content-XX-N.content-cms.com/api/000-...444";
   
// Acoustic Content API Endpoints, as found in  API Reference here:  
// https://developer.goacoustic.com/acoustic-content/reference
    static String deliveryContent = "/delivery/v1/content/";  
    static String authoringContent = "/authoring/v1/content/";
    static String loginEndpoint = "/login/v1/basicauth";
// Content Id for one of the sample articles from the sample package at: 
// https://github.com/acoustic-content-samples/sample-article-content
    static String contentId = "b7abe31d-7763-41a9-b8d5-f7cf78565cbd";
// Username to test the authenticated authoring APIs with (not needed for delivery APIs)  
// Get this from user input or more secure location, for an actual application 
    static String username = "[email protected]"; 
    static String password = "mypassword";

Create methods to call the delivery and authoring services

Use the following sample code for creating methods to call the delivery and authoring services.

/* Retrieve specified content item from authoring content service */  
    public String getAuthoringContent(String contentId) throws IOException {  
        return getWCHArtifact(authoringContent, contentId); 
    }
    /* Retrieve specified content item from delivery content service */ 
    public String getDeliveryContent(String contentId) throws IOException {  
          return getWCHArtifact(deliveryContent, contentId); 
    }

    /* Retrieve a Acoustic Content JSON artifact from specified endpoint by id */  
    public String getWCHArtifact(String endpoint, String id) throws IOException {  
        URL url = new URL(myTenantBaseAPIURL + endpoint + "/" + id);  
        HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
        connection.setUseCaches(false); 
        connection.connect();  
        return getResponse(connection); 
    }

    /* Login to Acoustic Content basicauth endpoint, for access to Authoring Services */  
    public String login(String username, String password) throws IOException {  
          String auth = Base64.getEncoder().encodeToString((username + ":" + password).getBytes("UTF-8")); 
         URL url = new URL(myTenantBaseAPIURL + loginEndpoint); 
         HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
         connection.setUseCaches(false); 
         connection.setRequestProperty("Authorization", "Basic " + auth);  
         connection.connect(); 
         return getResponse(connection);  
    }

Get the Content API response from the HttpURLConnection

In an actual application use a JSON library to help parse the response JSON and access fields. For the purpose of this tutorial, the following code shows you how to retrieve the JSON and print it out.

/* Get the response as a String or throw Exception with error response if http err code */  
    private String getResponse(HttpURLConnection connection) throws IOException {  
       BufferedReader in = null; 
       String res; 
       int responseCode = connection.getResponseCode();  
       try { 
           InputStream inputStream;  
           if (responseCode == 200) 
               inputStream = connection.getInputStream();  
           else  
              inputStream = connection.getErrorStream(); 
         in = new BufferedReader(new InputStreamReader(inputStream));  
           StringBuilder strb = new StringBuilder();  
           String line;  
           while ((line = in.readLine()) != null) 
                 strb.append(line + '\n');  
           res = strb.toString(); 
      } finally {  
            if (in != null) in.close(); 
      } 
       if (responseCode != 200) 
         throw new RuntimeException(res); 
      return res;  
    }

Retrieve content from delivery and authoring content service

The following code uses the methods created above to retrieve a specified content item by ID from the unauthenticated delivery service and then to login and retrieve the same content from the authoring environment.

📘

Note:

In an actual application you would include more logic for handling the response as a JSON object, include additional error handling, and retrieve user credentials from a more secure location if authentication is required.

// We'll start with a fairly lenient cookie manager for this simple sample and accept all cookies from these URLs  
    CookieManager cookieManager = new CookieManager(null, CookiePolicy.ACCEPT_ALL);  
    CookieHandler.setDefault(cookieManager);
// Get and print out a specified content item from the delivery content service 
    System.out.println("Delivery Content: " + getDeliveryContent(contentId));
// Login to Acoustic Content with a user associated with a Acoustic Content tenant 
    System.out.println("WCH Login: " + login(username, password));
// Make an authenticated request to retrieve a specified content item from authoring content service 
// The default cookie manager we set above, will help transfer the login response cookies to this request 
    System.out.println("Authoring Content: " + getAuthoringContent(contentId));

//function openLang(evt, cityName) { // Declare all variables //var i, tabcontent, tablinks; // Get all elements with class="tabcontent" and hide them //tabcontent = document.getElementsByClassName("tabcontent"); //for (i = 0; i < tabcontent.length; i++) { // tabcontent[i].style.display = "none"; //} // Get all elements with class="tablinks" and remove the class "active" //tablinks = document.getElementsByClassName("tablinks"); //for (i = 0; i < tablinks.length; i++) { // tablinks[i].className = tablinks[i].className.replace(" active", ""); //} // Show the current tab, and add an "active" class to the button that opened the tab // document.getElementById(cityName).style.display = "block"; // evt.currentTarget.className += " active"; //} //$('a[data-toggle="pill"]').on('shown.bs.tab', function (e) { // $(e.target).removeClass( "light-blue" ); // $(e.relatedTarget).addClass( "light-blue" ); //}) // collapsible blocks // var coll = document.getElementsByClassName("collapsible"); // var i; // for (i = 0; i < coll.length; i++) { // coll[i].addEventListener("click", function() { // this.classList.toggle("active"); // var content = this.nextElementSibling; // if (content.style.maxHeight){ // content.style.maxHeight = null; // } else { // content.style.maxHeight = content.scrollHeight + "px"; } // }); // }