OJET: Calling a REST Service

During my journey from a pure Java EE / Jakarta EE developer using JAX-RS, JSON-B, Jersey etc...  for Java - REST integration to JavaScript (in this case Oracle JET) I was checking the alternatives of calling REST services from JavaScript.

Things has changed a lot since I was doing mostly Vanilla and JQuery JavaScript for some "quick fixes".

Here I bring examples of making a GET request to a REST Service. The rest of operations only needs little bit more configuration, but this post is just to have a look into history in JavaScript and ways of calling a REST service (only making a GET, not a POST, PUT or DELETE)

If you want to execute the code: https://github.com/DanielMerchan/ojet-examples

It is fundamental that you read about JavaScript Promise Object and have a fully understand on it.

Vanilla JavaScript < ES6+

Yes, during my career I had to deal with JavaScript in its early stages to make AJAX calls and requests.

Basically this makes use of XMLHttpRequest JavaScript class.

// 1. GET Call Using Vanilla JavaScript - Asynchronous
const xhr = new XMLHttpRequest();
xhr.open('GET','https://apex.oracle.com/pls/apex/oraclejet/lp/activities/',true); // True marks it as Asyncrhonous
xhr.onreadystatechange = () => {
if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
console.log("GET VANILLA JAVASCRIPT RESPONSE");
// Call your Function to treat the JSON and operate with it
const activities = JSON.parse(xhr.responseText).items;
activities.forEach(activity => {
console.log(`Activity 1: ${activity.name}`);
})
} else if (xhr.status === 500) {
console.log("Error: " + xhr.status + " " + xhr.statusText);
}
}
// GET, nothing to send (in POST, PUT operations is where the information is sent)
// xhr.setRequestHeader('Authorization', 'Bearer ' + jwtoken); If needed, add Headers
xhr.send();


JQuery $ajax, $get, $post, $getJSON

JQuery has been always there to simplify our lifes usng JavaScript. It also included its wrappers for making AJAX calls by using $ajax.

Now, we have powerful operation such us $getJSON which directly returns the JSON of a GET operation as follows.

// 2. GET Call Using JQuery - Aysynchronous
$.getJSON('https://apex.oracle.com/pls/apex/oraclejet/lp/activities/', activitiesResponse => {
const activities = activitiesResponse.items;
console.log("GET JQUERY JAVASCRIPT RESPONSE");
activities.forEach(activity => {
console.log(`Activity 2: ${activity.name}`);
});
}).fail(function (xhr, status, error) {
console.log("Error: " + status + " " + error + " " + xhr.status + " " + xhr.statusText);
});
Also JQuery now is 100% aligned with JavaScript Promise.

ES6+ JavaScript. Fetch and await

Now there is a very clean way of calling REST by using fetch and await keywords. Fetch makes an asynchronous call to the REST service and await is used to wait till a response is done.

Here two examples calling an Asynchronous Function and other without calling an Asynchronous function.

[gist

// 3.A GET Using Fetch and Await Async
self.fetchActivitiesAsync = async () => {
try {
const response = await fetch('https://apex.oracle.com/pls/apex/oraclejet/lp/activities/');
if (response.ok) {
console.log("GET FETCH/AWAIT using JAVASCRIPT ASYNC Function");
const jsonResponse = await response.json();
return jsonResponse;
}
throw new Error('Request Failed');
} catch (error) {
console.log(error);
}
};
// 3.A Call the Asynchronous Function declared above
self.fetchActivitiesAsync().then(activities => activities.items.forEach(activity => {
console.log(`Activity 3.A: ${activity.name}`);
})).catch(error => {
console.log(error);
});
// 3.B Without function
fetch('https://apex.oracle.com/pls/apex/oraclejet/lp/activities/').then(activitiesResponse => {
console.log("GET using FETCH which is asynchronous without an extra function");
if (activitiesResponse.ok) {
activitiesResponse.json().then(activitiesJson => {
activitiesJson.items.forEach(activity => {
console.log(`Activity 3.B: ${activity.name}`);
})
})
}
});
If you need to make multiple calls I will recommend the usage of a async wrapper function and the usage await inside of it for "readable code".

Comments

Popular posts from this blog

OJET: Build and Deploy in an Application Server

OJET: Select All options using only Checkboxset

OFMW: 12.2.1.4 Released