Open In App

HTTP REST API Calls in ElectronJS

ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime.

We already know about the importance of HTTP REST API’s in any system. They are used everywhere globally and there are dedicated resources available on the internet that cover everything regarding HTTP REST API’s, standards, and protocols in detail. Some of the more famous resources for HTTP REST are mentioned here and here. NodeJS provides extensive support for making HTTP REST API calls via built-in modules and external packages. NodeJS provides us with built-in HTTP and HTTPS modules and some of the most famous npm packages used in NodeJS are axios, request and node-fetch. Since Electron is essentially a Node application, all of the above-mentioned packages are supported and can be used in Electron as well. For a short tutorial on how to use axios package in Electron for making REST API calls, Refer the article: Geo Information in ElectronJS. In addition to the above, Electron also provides us with a built-in net Module for this very purpose. The net module is used for issuing HTTP/HTTPS REST requests using Chromium’s native networking library. This tutorial will demonstrate how to make HTTP REST API calls in Electron using the net module and the advantages and features of the net module. 



We assume that you are familiar with the prerequisites as covered in the above-mentioned link. For Electron to work, node and npm need to be pre-installed in the system.

The net Module is a client-side API in Electron for issuing HTTP/HTTPS requests. As mentioned above, It is similar to the HTTP and HTTPS modules of NodeJS but it uses Chromium’s native networking library instead of the NodeJS implementation and therefore offers better support for web proxies. Some other advantages of the net Module are: 



Project Structure: 

Example: Follow the Steps given in Dynamic Styling in ElectronJS to set up the basic Electron Application. Copy the Boilerplate code for the main.js file and the index.html file as provided in the article. Also, perform the necessary changes mentioned for the package.json file to launch the Electron Application. We will continue building our application using the same code base. The basic steps required to set up the Electron application remain the same.

package.json: 

{
    "name": "electron-net",
        "version": "1.0.0",
            "description": "Making HTTP REST API Calls - net Module in Electron ",
                "main": "main.js",
                    "scripts": {
        "start": "electron ."
    },
    "keywords": [
        "electron"
    ],
        "author": "Radhesh Khanna",
            "license": "ISC",
                "dependencies": {
        "electron": "^8.3.0"
    }
}

Output: 

HTTP REST API Calls in Electron The net module in Electron is part of the Main Process. To import and use the net module in the Renderer Process, we will be using Electron remote module. In this tutorial, we have used httpbin.org which is a simple and free 3rd Party HTTP REST Request & Response Service. It provides sample HTTP REST API’s which are publicly available and do not require any authentication and authorization. It also provides many other features such as authentication tests, redirects, cookies, dynamic and randomized data, etc, through sample REST API’s. We will be making HTTP GET and HTTP POST Requests to this service for demonstration purposes using the net module. All the components used in the net Module including design and implementation such as Instance methods, Instance events and Instance properties are similar to NodeJS implementation. This net module can only be used after the ready event of the app module is emitted. This module is supported on all OS platforms and environments.




<h3>Making HTTP REST API Calls
    using net Module in Electron
</h3>
<button id="get">
    Make Sample GET Request
</button>
<br><br>
<button id="post">
    Make Sample POST Request
</button>
<!-- Adding Individual Renderer
    Process JS File -->
<script src="index.js"></script>




const electron = require('electron');
// Importing the net Module from electron remote
const net = electron.remote.net;
 
let get = document.getElementById('get');
get.addEventListener('click', () => {
    const request = net.request({
        method: 'GET',
        protocol: 'http:',
        hostname: 'httpbin.org',
        path: '/get',
        redirect: 'follow'
    });
    request.on('response', (response) => {
        console.log(`STATUS: ${response.statusCode}`);
        console.log(`HEADERS: ${JSON.stringify(response.headers)}`);
 
        response.on('data', (chunk) => {
            console.log(`BODY: ${chunk}`)
        });
    });
    request.on('finish', () => {
        console.log('Request is Finished')
    });
    request.on('abort', () => {
        console.log('Request is Aborted')
    });
    request.on('error', (error) => {
        console.log(`ERROR: ${JSON.stringify(error)}`)
    });
    request.on('close', (error) => {
        console.log('Last Transaction has occurred')
    });
    request.setHeader('Content-Type', 'application/json');
    request.end();
});
 
let post = document.getElementById('post');
post.addEventListener('click', () => {
    let body = JSON.stringify({ key: 1 });
    const request = net.request({
        method: 'POST',
        protocol: 'http:',
        hostname: 'httpbin.org',
        path: '/post',
        redirect: 'follow'
    });
    request.on('response', (response) => {
        console.log(`STATUS: ${response.statusCode}`);
        console.log(`HEADERS: ${JSON.stringify(response.headers)}`);
 
        response.on('data', (chunk) => {
            console.log(`BODY: ${chunk}`)
        });
    });
    request.on('finish', () => {
        console.log('Request is Finished')
    });
    request.on('abort', () => {
        console.log('Request is Aborted')
    });
    request.on('error', (error) => {
        console.log(`ERROR: ${JSON.stringify(error)}`)
    });
    request.on('close', (error) => {
        console.log('Last Transaction has occurred')
    });
    request.setHeader('Content-Type', 'application/json');
    request.write(body, 'utf-8');
    request.end();
});

Explanation: The net module supports only one Instance method. This net.request(options) Instance method uses the ClientRequest Instance. Every call to this Instance method is created and returns a new ClientRequest Instance. This instance method is used to issue both secure and insecure HTTP requests according to the specified protocol scheme in the options object. For more detailed information on the net.request() method. It takes in the following parameters. 

All Instance methods, events, and properties further used in the above code are part of the ClientRequest Instance. The ClientRequest Instance makes the actual HTTP/HTTPS requests and it implements the Writable Stream interface and is therefore an EventEmitter. A detailed Explanation of the ClientRequest constructor options is given below. It supports the following parameters: 

The ClientRequest Instance supports the following Instance Events. 

Additionally, the ClientRequest Instance supports a single Instance Property. 

Based on the ClientRequest constructor options and the Instance events and properties we have covered up till now, we notice that some critical parameters for HTTP requests are missing such as the headers and the body in case of the HTTP POST request. This is because these parameters were removed from the constructor options object from the previous versions of Electron and added as separate Instance methods in the newer versions. The ClientRequest Instance supports the following Instance Method. 

At this point, upon launching the Electron application, we should be able to make Successful HTTP REST API calls to the httpbin.org HTTP Service, GET and POST Sample APIs and check the responses that we are getting from these APIs. 

Output: 


Article Tags :