Overview

Skill Level: Any

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 Watson Content Hub APIs.

Prerequisites

Get familiar with the Acoustic Content APIs

  • Acoustic 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 Acoustic Content REST API URLs is {API URL}/{WCH API endpoint}.¬†

The API URL is constructed as Domain name/{path} where {path}= api/{Content hub ID}.

The API endpoints are described in the Acoustic 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 Acoustic Content user interface. Open the specific content item that you want and click the API information icon below the content.

    ItemId = “b7abe31d-7763-41a9-b8d5-f7cf78565cbd”

  2. Provide the Item ID in the delivery API: {APIURL}/delivery/v1/content/{Item ID}.

https://my12.digitalexperience.ibm.com/api/12345678-…-56789abcdef0/delivery/v1/content/’b7abe31d-7763-41a9-b8d5-f7cf78565cbd’

 

For more information about Acoustic Content and all the available Acoustic Content developer tutorials, click here.

Step-by-step

  1. Get the API URL for your tenant

    You can get your API URL for your tenant from the Acoustic Content Authoring UI.

    1. From the ribbon click About.
    2. Click Hub information. The API URL is displayed in the Hub information window. Your tenant API URL would look similar to: APIURL : https://{Domain name}/api/{ContenthubID}

  2. 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;

  3. Define the constants

     Define the constants for the Acoustic Content API URL, Acoustic 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://my11.digitalexperience.ibm.com/api/000-…444”;

    // Acoustic Content API Endpoints, as found in  API Explorer here:
    // https://developer.ibm.com/api/view/id-618:title-IBM_Watson_Content_Hub_API#doc
    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/ibm-wch/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 = “myusername@mycompany.com”;
    static String password = “mypassword”;

  4. 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);
    }

     

  5. Get the Acoustic 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;
    }

  6. 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 Watson Content Hub with a user associated with a WCH 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));

Expected outcome

For more information about Acoustic Content and all the available Acoustic Content developer tutorials, click here.

Join The Discussion

Your email address will not be published. Required fields are marked *