Tuesday, 16 April 2019

Connecting to SDL WorldServer using the REST API

It is now possible to connect to SDL WorldServer and perform a number of actions by using the WorldServer REST API. The REST API documentation is available from your WorldServer instance by accessing <serverURL>:<portnumber>/ws-api/docs/ws-api-doc-v1.html.

In this article I present a method for connecting to SDL WorldServer and fetching a security token to be used in all subsequent API calls.

public static String getSecurityToken(String wsBaseUrl, String username, String password) throws IOException {
StringBuilder loginJson = new StringBuilder();
loginJson.append("{");
loginJson.append("\"username\":\"" + username + "\",");
loginJson.append("\"password\":\"" + password + "\"");
loginJson.append("}");
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPostRequest = new HttpPost(wsBaseUrl + "/ws-api/v1/login");
httpPostRequest.setHeader(new BasicHeader("Content-Type", "application/json"));
httpPostRequest.setHeader(new BasicHeader("Accept", "application/json"));
httpPostRequest.setEntity(new StringEntity(loginJson.toString()));
HttpResponse response = httpClient.execute(httpPostRequest);
Gson gson = new GsonBuilder().create();
JsonObject jsonLoginResponse = gson
.fromJson(new InputStreamReader(response.getEntity().getContent()), JsonObject.class);
return jsonLoginResponse.getAsJsonPrimitive("sessionId").getAsString();
}
The method takes three parameters:
  1. wsBaseUrl
  2. username
  3. password
The wsBaseUrl must be the <serverURL>:<portnumber> where your WorldServer instance is running. The login method will append the "/ws-api/v1/login" path required for invoking the REST based login call.

As mentioned earlier, the call returns a security token to be used in all subsequent API calls.

No comments:

Post a Comment