Calling REST APIs

Started by Thomas Rohde, February 20, 2023, 09:34:41 AM

Previous topic - Next topic

Thomas Rohde

I struggle with creating a REST API client call just using pure Javascript without escaping to Java GraalVM interop.

Is it at all possible, or should I use Java http connections?

Jean-Baptiste Sarrodie


I don't think it's possible to do it in pure javascript, so it most certainly have to rely on some java code through GraalVM or Nashorn interop.

I think (but haven't tested it) that if we where able to create a good java implementation of XMLHttpRequest made available to jArchi (either using jav code from js, or by adding it natively into the API), then it would become possible to use other libraries such as axios.

Here is a potential candidate (nashorn polyfill):

Another one (need to hack source code of GWT):

Or maybe this one:



If you value and use Archi please consider making a donation!


I had the same question in the past. Browsing through other examples, I found this snipped and altered it to call a JSON rest API. Maybe you can use it too (works with GraalVM)

function CallApi(url) {

    var imports = new JavaImporter(, java.util, java.lang,
    var result=""

    with (imports) {

        var urlObj =  new URL(url)
        var hcon   = urlObj.openConnection()

        hcon.setRequestProperty ("Accept", "application/json")
        hcon.setRequestProperty ("Accept-Charset", "UTF-8")
        hcon.setRequestProperty ("Accept-Language", "NL")

        try {
            var reader = new BufferedReader(new InputStreamReader(hcon.getInputStream()))

            var line = reader.readLine()
            while (line != null) {
                result += line + "\n"
                line = reader.readLine()
            result = JSON.parse(result)
            if (("RESULT"===result.kind)&&("OK"===result.status)) {
                //console.log("API call to"+url+" wend well")
            } else {
                console.log("error in API call response")
        } catch(e) {
            console.log("HTTPS error:")
    return result

if API needs standard HTTPS username/password insert this when creating headers (of course, replace/set "Username" and "Password":
userCredentials = Username +":" +Password
basicAuth       = "Basic " + new String(Base64.getEncoder().encode(userCredentials.getBytes()))
hcon.setRequestProperty ("Authorization", basicAuth)

if REST API needs cookie, add this to the code

Retrieving cookie from call:

Using cookie
hcon.setRequestProperty ("Cookie", cookie)