Oracle Application Container Cloud Service: Building a RESTful API with Node.js and Express
Purpose
This tutorial shows you how to develop a RESTful API in Node.js using the Express framework and an Oracle Database Cloud Service instance to deploy it in Oracle Application Container Cloud Service.
This article describes how a simple Node.js application is configured for deployment on the Oracle Application Container Cloud and how it leverages the node-oracledb database driver that allows Node.js applications to easily connect to an Oracle Database. From the Application Container Cloud, the application discussed uses a cloud Service Binding to access a DBaaS instance also running on the Oracle Public Cloud. The Node.js application returns a JSON message containing details about employee in the EMPLOYEE table in the HR schema of the DBaaS instance. The Node.js application itself is very rudimentary. The way it handles the HTTP requests is quite simplistic. It does not leverage most common practices in Node.js or JavaScript. It does not handle bind parameters in the queries nor does it interpret URL path parameters or query parameters.
This article describes how a simple Node.js application is configured for deployment on the Oracle Application Container Cloud and how it leverages the node-oracledb database driver that allows Node.js applications to easily connect to an Oracle Database. From the Application Container Cloud, the application discussed uses a cloud Service Binding to access a DBaaS instance also running on the Oracle Public Cloud. The Node.js application returns a JSON message containing details about employee in the EMPLOYEE table in the HR schema of the DBaaS instance. The Node.js application itself is very rudimentary. The way it handles the HTTP requests is quite simplistic. It does not leverage most common practices in Node.js or JavaScript. It does not handle bind parameters in the queries nor does it interpret URL path parameters or query parameters.
Time to Complete
45 minutes
Background
Express is a Node.js web application framework that provides a robust set of features to develop web and mobile applications. It facilitates a rapid development of Node based Web applications.
Scenario
In this tutorial, you build a basic RESTful API that implements the CRUD (Create, Read, Update, and Delete) operations on an employee table in a Oracle Database Cloud Service instance using plain Node.js and the Express framework.
The Node.js RESTful application responds to the following endpoints:
| Path | Description |
|---|---|
| GET: /employees | Gets all the employees. |
| GET: /employees/{searchType}/{searchValue} | Gets the employees that match the search criteria. |
| POST: /employees | Adds an employee. |
| PUT: /employees/{id} | Updates an employee. |
| DELETE: /employees/{id} | Removes an employee. |
Copy the following script into the SQL worksheet to create the
EMPLOYEE table and the sequence named EMPLOYEE_SEQ:CREATE TABLE EMPLOYEE (
ID INTEGER NOT NULL,
FIRSTNAME VARCHAR(255),
LASTNAME VARCHAR(255),
EMAIL VARCHAR(255),
PHONE VARCHAR(255),
BIRTHDATE VARCHAR(10),
TITLE VARCHAR(255),
DEPARTMENT VARCHAR(255),
PRIMARY KEY (ID)
);
CREATE SEQUENCE EMPLOYEE_SEQ
START WITH 100
INCREMENT BY 1;
- Click Run Script.

Description of this image - Click Commit.

Description of this image - Copy the following script into the SQL worksheet to insert five employees, click Run Script, and then click Commit.
INSERT INTO EMPLOYEE (ID, FIRSTNAME, LASTNAME, EMAIL, PHONE, BIRTHDATE, TITLE, DEPARTMENT) VALUES (EMPLOYEE_SEQ.nextVal, 'Hugh', 'Jast', 'Hugh.Jast@example.com', '730-715-4446', '1970-11-28' , 'National Data Strategist', 'Mobility'); INSERT INTO EMPLOYEE (ID, FIRSTNAME, LASTNAME, EMAIL, PHONE, BIRTHDATE, TITLE, DEPARTMENT) VALUES (EMPLOYEE_SEQ.nextVal, 'Toy', 'Herzog', 'Toy.Herzog@example.com', '769-569-1789','1961-08-08', 'Dynamic Operations Manager', 'Paradigm'); INSERT INTO EMPLOYEE (ID, FIRSTNAME, LASTNAME, EMAIL, PHONE, BIRTHDATE, TITLE, DEPARTMENT) VALUES (EMPLOYEE_SEQ.nextVal, 'Reed', 'Hahn', 'Reed.Hahn@example.com', '429-071-2018', '1977-02-05', 'Future Directives Facilitator', 'Quality'); INSERT INTO EMPLOYEE (ID, FIRSTNAME, LASTNAME, EMAIL, PHONE, BIRTHDATE, TITLE, DEPARTMENT) VALUES (EMPLOYEE_SEQ.nextVal, 'Novella', 'Bahringer', 'Novella.Bahringer@example.com', '293-596-3547', '1961-07-25' , 'Principal Factors Architect', 'Division'); INSERT INTO EMPLOYEE (ID, FIRSTNAME, LASTNAME, EMAIL, PHONE, BIRTHDATE, TITLE, DEPARTMENT) VALUES (EMPLOYEE_SEQ.nextVal, 'Zora', 'Sawayn', 'Zora.Sawayn@example.com', '923-814-0502', '1978-03-18' , 'Dynamic Marketing Designer', 'Security');
In this section, you create the REST Service and you use the NPM utility to download and build dependencies for your Node.js project.
- Open a console window and go to the folder where you want to store the Node.js application server.

Description of this image - Run
npm initto create thepackage.jsonfile. At the prompt, enter the following values, confirm the values, and then press Enter:- Name:
node-server - Version:
1.0.0(or press Enter.) - Description:
Employee RESTful application - Entry point:
server.js - Test command (Press Enter.)
- Git repository (Press Enter.)
- Keywords (Press Enter.)
- Author (Enter your name or email address.)
- License (Press Enter.)

Description of this image Thepackage.jsonfile is created and stored in the current folder. You can open it and modify it, if needed. - Name:
- In the console window, download, build, and add the Express framework dependency:
npm install --save express

Description of this image - In the console window, install the
body-parserdependency:npm install --save body-parser
Thebody-parserdependency is a Node.js middleware for handling JSON, Raw, Text and URL encoded form data.
Description of this image Note: If the console displaysoptional, dep failed or continuingoutput, ignore it. The output pertains to warnings or errors caused by dependencies on native binaries that couldn't be built. The libraries being used often have a JavaScript fallback node library, and native binaries are used only to optimize performance. - Open the generated
package.jsonfile in a text editor, and verify its contents. It should look like this:
- Create a
server.jsfile, open it in a text editor, and add the followingrequirestatements to use the node dependencies and theoracledbserver component: - Add a
PORTvariable equal either to theprocess.env.PORTenvironment variable or to 8089, if the environment variable isn't set:ThePORTenvironment variable is set automatically by Oracle Application Container Cloud Service. - Create an
appvariable to use theexpressmethod: - Store the database connection properties that are equal to environment variables or defaults:The environment variables listed are set in Oracle Application Container Cloud Service automatically when you add the Database Cloud Service binding.
- Create the
doReleasemethod to release the database connection: - Configure your application to use
bodyParser(), so that you can get the data from aPOSTrequest: - Create a router object and assign it to the
routervariable: - Add the following response headers to support calls from external clients:Note: Browsers and applications usually prevent calling REST services from different sources. If you run the client on Server A and the REST services on Server B, then you must provide a list of known clients in Server B by using the
Access-Controlheaders. Clients check these headers to allow invocation of a service and prevent cross-site scripting attacks (XSS). - Create the
GETmethod to get the list of employees:
- Create the
GETmethod to return the list of employees that match the criteria./** * GET /searchType/searchValue * Returns a list of employees that match the criteria */ router.route('/employees/:searchType/:searchValue').get(function (request, response) { console.log("GET EMPLOYEES BY CRITERIA"); oracledb.getConnection(connectionProperties, function (err, connection) { if (err) { console.error(err.message); response.status(500).send("Error connecting to DB"); return; } console.log("After connection"); var searchType = request.params.searchType; var searchValue = request.params.searchValue; connection.execute("SELECT * FROM employee WHERE "+searchType+" = :searchValue",[searchValue], { outFormat: oracledb.OBJECT }, function (err, result) { if (err) { console.error(err.message); response.status(500).send("Error getting data from DB"); doRelease(connection); return; } console.log("RESULTSET:" + JSON.stringify(result)); var employees = []; result.rows.forEach(function (element) { employees.push({ id: element.ID, firstName: element.FIRSTNAME, lastName: element.LASTNAME, email: element.EMAIL, phone: element.PHONE, birthDate: element.BIRTHDATE, title: element.TITLE, dept: element.DEPARTMENT }); }, this); response.json(employees); doRelease(connection); }); }); }); - Create the
POSTmethod to add employees:
- Create the
PUTmethod to update the employee by ID:
- Create the
DELETEmethod to remove employees by ID:
- Set up and start the server:
The completed
server.js should look like this:
To ensure that your server application runs correctly in the cloud, you must:
- Bundle the application in a
.zipfile that includes all dependencies.
Note: Don't bundle database drivers for Oracle Enterprise Cloud Service. - Include a
manifest.jsonfile that specifies the command which Oracle Application Container Cloud Service should run. - Ensure your application listens to requests on a port provided by the
PORTenvironment variable. Oracle Application Container Cloud Service uses this port to redirect requests made to your application.
Creating the manifest.json File
When you upload your application to Oracle Application Container Cloud Service using the user interface, you must include a file called
manifest.json in the application archive (.zip, .tgz, .tar.gz file). If you use the REST API to upload the application, this file is still required but doesn’t have to be in the archive.- Create a
manifest.jsonfile. - Open the
manifest.jsonfile in a text editor and add the following content:Themanifest.jsonfile contains the target platform and the command to be run. - Compress all the project files including the
manifest.jsonfile and thenode_modulesfolder in a file namednode-app-db.zip. Make sure that thenode_modulesfolder doesn't have an OracleDB subfolder.
To deploy the application to Oracle Application Container Cloud Service, use the
node-app-db.zip file that you created in the previous section.- Log in to Oracle Cloud at http://cloud.oracle.com/. Enter the identity domain, user name, and password for your account.

Description of this image - Click Service Console to open the Oracle Application Container Cloud Service console.

Description of this image - In the Applications list view, click Create Application and select Node.

Description of this image - In the Application section, enter a name for your application, select Upload application archive, and click Browse.

Description of this image - On the File Upload page, select the
node-app-db.zipfile, and click Open. After a short delay, the application is verified.
Description of this image - In the Application section, enter
Simple Rest Service that implements HTTP POST and HTTP Get methodsin the Notes field and click Create.
Description of this image - When the confirmation dialog box is displayed, click OK.

Description of this image Your application could take a few minutes to deploy.
- Open a web browser and enter the URL of the employee REST service.Note: Replace
identity-domainwith the entity domain of your cloud account.URL:https://employees-service-identity-domain.apaas.us2.oraclecloud.com/employees
Note: If you would like to test your on service over the local machine then You need to follow below steps to run the same code over the machine.
- Install Oracledb driver where your folder is reside.
- Now Run your application. Node server.js
Additional information: Code to know the server address where your application is hosted over the local machine. You need to just add the code in the end to know the details of the server.
No comments:
Post a Comment
Thanks for the comments. I`ll get back to you shortly.
Regards
Tushar