Call unauthenticated and authenticated APIs
Learn how to call Content APIs in Java, NodeJS, and Javascript
Overview
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 Acoustic Content APIs.
Before you begin
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 asDomain 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
- 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"
- 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));
Get the API URL for your subscription
You can get your API URL from the Acoustic 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
.
Retrieve content from delivery content service
Use the request-promise node module to retrieve content from delivery content service
The sample code uses request-promise
node module, you can use any Node module that works best for you.
- In your NodeJS project add a dependency on request-promise, or similar HTTP request package to your package.json, or npm install the package directly.
Note:
Request-promise requires a sibling dependency on the Node JS request module.
`_npm install request_ `
`_npm install request-promise_`
- Define the base API URL, the Content delivery content URL, and a variable referring to the ID of a published content item.
_const request = require("request-promise").defaults({jar: true});_
_const baseTenantAPIURL = "https://content-XX-N.content-cms.com/api/00000000-...4444";_
_const deliveryContentURL = baseTenantAPIURL + "/delivery/v1/content/";_
_const contentId = 'b7abe31d-7763-41a9-b8d5-f7cf78565cbd';_
- Retrieve a published content item from the delivery content service with a simple Node JS function.
_function getDeliveryContentById(contentId) {_
_ return request({uri: deliveryContentURL + contentId, json: true});_
_}_
- Print the retrieved content item to the console.
Note:
An actual application would include additional error handling functionality and application-specific logic with the metadata returned in the content item.
_getDeliveryContentById(contentId)._
_ then(content => console.log(JSON.stringify(content, null, ' ')))._
_ catch(err => console.log("Error retrieving delivery content:" + JSON.stringify(err)));_
Retrieve content from authoring content service
Use the request-promise node module to log in and retrieve content from authoring content service
You must log in to Acoustic Content to use the Authoring service API as an authenticated user with a role as Editor, Manager, or Admin. You can log in with the /login/v1/basicauth
REST API.
- Define the login and authoring content URLs in addition to the API URL for your subscription and the variable referring to the ID of a content item.
_const authoringContentURL = baseTenantAPIURL + "/authoring/v1/content/";_
_const loginURL = baseTenantAPIURL + "/login/v1/basicauth";_
- Login and to get content from the authoring content service with a simple Node JS function
_function getAuthoringContentById(contentId) {_
_ return request({uri: authoringContentURL + contentId, json: true});_
_}_
_function login(username, password) {
_ return request({uri: loginURL, json:true,_
_ auth:{"user":username,"pass":password,"sendImmediately": true}});_
_}_
- Login, retrieve, and print the JSON response for an authoring content item.
_login("[email protected]", "myWCHPassword")._
_ then(res => getAuthoringContentById(contentId))._
_ then(content => console.log(JSON.stringify(content, null, ' ')))._
_ catch(err => console.log("Error retrieving authoring content:" + JSON.stringify(err)));_
Get the API URL for your tenant
You can get your API URL for your tenant 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
.
Retrieve content from delivery content service
Use the sample Content API JS helper to retrieve content from delivery content service
The sample wchhelper.js
provides a simple wrapper that you can use to construct an instance of the helper for a specific tenant API URL. The sample wchhelper.js makes the REST API calls, handles the xhr
request, and the JSON parsing of the response for you.
- Download the sample wchhelper.js helper to a local web application project file as js/wchhelper.js
- Load it with
<script src="js/wchhelper.js">
- Construct an instance of the sample helper with the tenant-specific API URL. For example:
let options = {
url: "https://{Domain name}/api/{ContentID}",
debug: true
};
wchHelper = new WchHelper(options);
- Use the helper to retrieve and display the JSON response for a content item. For example:
contentId = 'b7abe31d-7763-41a9-b8d5-f7cf78565cbd';
wchHelper.getDeliveryContentById(contentId)
.then(content => { alert("Delivery Content response: " + JSON.stringify(content, null, ' ')) })
.catch(err => { alert("getDeliveryContentById encountered an error: " + err); });
Retrieve content from authoring content service
Use the sample Content API JS helper to log in and retrieve content from authoring content service
You must log in to Content to use the Authoring service API as an authenticated user with a role as Editor, Manager, or Admin. You can use the sample wchhelper.js to log in.
- Construct an instance of the sample helper with the tenant-specific API URL. For example:
let options = {
url: "https://{Domain name}/api/{ContentID}",
debug: true
};
wchHelper = new WchHelper(options);
- Make a call and pass the user name and password for the Content user to log in.
- After successfully logging in, the wchhelper.js calls to retrieve and display the JSON response for an authoring content item. For example:
contentId = 'b7abe31d-7763-41a9-b8d5-f7cf78565cbd';
wchHelper.login('[email protected]', 'myPassword')
.then(tenantId => wchHelper.getAuthoringContentById(contentId))
.then(acontent => { alert("Authoring Content response: " + JSON.stringify(acontent, null, ' ')) })
.catch(err => { alert("getAuthoringContentById encountered an error: " + err); });
Updated almost 2 years ago