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.



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.

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

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: Inter-Module communication in TypeScript Template

OJET: Build and Deploy in an Application Server

OJET: Select All options using only Checkboxset