NodeJS API Documentation

In this blog, we will discuss NodeJS API documentation. Before that, we need to know about the API.

Let’s talk about API:

In the development cycle while using a specific stack (a combination of DB, middleware, and front end) lots of code is repetitive, like connecting to databases, performing CRUD operations, handling databases, converting raw data to objects. In each and every application these operations are there, then why do this, again and again, we can use a template that will do this for developers. This is API (Application Program Interface).

The development of apps for mobile devices meant that organizations needed to allow users to access information through apps and not just through the Internet. Within the public sector, APIs are the only things to allow agencies to share easily information and also lets the public interact.

Simply, it’s a medium to communicate software to software.

 

There are the same web service APIs: 

  1. SOAP
  2. XML-RPC: This is a protocol that uses a specific XML format to transfer data compared to SOAP that uses a proprietary XML format. It is also older than SOAP. XML-RPC uses minimum bandwidth and is much simpler than SOAP
  3. JSON-RPC: This protocol is similar to XML-RPC but instead of using XML format to transfer data it uses JSON.
  4. REST

SOAP: Simple Object Access Protocol

In the short-to-medium-term future, SOAP will likely continue to be used for enterprise-level web services that require high security and complex transactions. APIs for financial services, payment gateways, CRM software, identity management, and telecommunication services are commonly used examples of SOAP.

One of the most well-known SOAP APIs is PayPal’s public API that allows you to accept PayPal and credit card payments. Add a PayPal button to your website, let users log in with PayPal, and perform other PayPal-related actions.

Ex:

REST: Representational State Transfer

A RESTful API is an application program interface (API) that uses HTTP requests to GET, PUT, POST, and DELETE data.

Nowadays, REST is the most popular choice for developers to build public APIs. You can find many examples on the internet, especially since all big social media sites provide REST APIs so that developers can seamlessly integrate their apps with the platform. These public APIs also come with detailed documentation where you can get all the information you need to pull data through the API.

REST services are useful for restricted profile devices, such as mobile, and are easy to integrate with existing websites.

Ex:

Different between REST and SOAP

Now talk about node js API(s):

 

We can write two types of API in nodejs


1> Blocking / Synchronously

2> Non- blocking / Asynchronously

Blocking / Synchronous Code:


const fs = require('fs');

const data = fs.readFileSync('/file.md'); // blocks here until file is read

console.log(data);

console.log("Program Ended");

O/P:

file content(Program Ended)

Here in this example, we can see that data will be consoled after the file is read. That means when the file will successfully read then the data will console.

Non-blocking / Asynchronous Code:


const fs = require('fs');

fs.readFile('/file.md', (err, data) => {

if (err) throw err;

console.log(data);

});

console.log("Program Ended");

O/P:

file content(Program Ended)

Here we can see we set two parameters in this readFile function err and data. If the file is not present or any problem occurs to read this file then the error will throw. But shows that the program does not wait for file reading and proceeds to print "Program Ended" and at the same time, the program without blocking continues reading the file. When the file will read successfully then the program callback the readFile function and print the file content. Pass the error to a callback, a function provided specifically for handling errors and the results of asynchronous operations.

Most asynchronous methods exposed by the Node.js core API follow an idiomatic pattern referred to as an error-first callback. When the operation either completes or an error is raised, the callback function is called with the Error object passed as the first argument. If no error was raised, the first argument will be passed as null.

So, this is very important for writing an API with proper error handling.

 

How we handle the error in nodejs:

Errors in Node.js are handled through exceptions. An exception is created using the throw keyword:

throw value

Usually in client-side code value can be any JavaScript value including a string, a number or an object. In Node.js, we don’t throw strings, we just throw Error objects.

An error object is an object that is either an instance of the Error object, or extends the Error class, provided in the Error core module:

throw new Error('This is a error')

OR

class NotEnoughCoffeeError extends Error {

//...

}

throw new NotEnoughCoffeeError

An exception handler is a try/catch statement.

Any exception raised in the lines of code included in the try block is handled in the corresponding catch block:

try {

//lines of code

} catch (e) {

}

//e in this example is the exception value.

You can add multiple handlers, that can catch different kinds of errors.

All JavaScript errors are handled as exceptions that immediately generate and throw an error using the standard JavaScript throw mechanism. These are handled using the try…catch construct provided by the JavaScript language.

try {

const m = 1;

const n = m + z;

} catch (err) {

console.error(err);

}

 

o/p : ReferenceError: z is not defined

Uncaught exceptions

Node.js follows a callback pattern where an error object is the first argument and data is the second argument. It is not uncommon to see examples in the documentation where an error is thrown if an error is returned by the callback.

var fs = require('fs');

 

fs.readFile('somefile.txt', function (err, data) {

if (err) throw err;

console.log(data);

});

If we run this and assuming we have no file called ‘somefile.txt’ there will be an error.

Error: ENOENT, open 'somefile.txt'

This has the effect of crashing the process and bringing down the whole application. This is by design. Node.js does not separate your application from the server.

This is an uncaught exception. Gets thrown during the execution of your program, your program will crash.

To solve this, you listen for the uncaughtException event on the process object:


process.on('uncaughtException', (err) => {

console.error('There was an uncaught error', err)

process.exit(1) //mandatory (as per the Node docs)

})

You don’t need to import the process core module for this, as it’s automatically injected.

Exceptions with promises

Using promises you can chain different operations, and handle errors at the end:


doSomething1()

.then(doSomething2())

.then(doSomething3())

.catch(err => console.error(err))

How do we know where the error occurred? We don’t know, but we can handle errors in each of the functions we call (doSomethingX function), and inside the error, the handler throws a new error, that’s going to call the outside catch handler:

const doSomething1 = () => {

//...

try {

//...

} catch (err) {

//... handle it locally

throw new Error(err.message)

}

//...

}

To be able to handle errors locally without handling them in the function we call, we can break the chain we can create a function in each then() and process the exception:

doSomething1

.then((() => {

return doSomething2().catch(err => {

//handle error

throw err //break the chain!

})

})

.then((() => {

return doSomething2().catch(err => {

//handle error

throw err //break the chain!

})

})

.catch(err => console.error(err))

Error handling with async/await

Using async/await, we still need to catch errors, and we do it this way:

async function someFunction() {

try {

await someOtherFunction()

}

catch (err) {

console.error(err.message)

}

}

And that’s how we can handle the error of any node js API(s) or any nodejs program. But there are some more things we have to know after throw errors. The errors have to be specific. Every API(s) has multiple errors that occurred then we have to specify them. For that we user error message, error.stack and error node

Error message:

By using error.message property we can define the error messages.

The error.message property is the string description of the error as set by calling new Error(message).

const err = new Error('The message');

console.error(err.message);

 

// Prints: The message

Error stack :

The error.stack property is a string describing the point in the code at which the Error was instantiated.

const err = new Error('The message');

console.log(err);

console.los(err.stack);

// Prints: The message

o/p:

{ stack: [Getter/Setter],

  arguments: undefined,

  type: undefined,

  message: 'The message' }

Error: The message

    at Object. (/home/nico/example.js:1:75)

    Module._compile (module.js:407:26)

    at Object..js (module.js:413:10)

    Module.load (module.js:339:31)

    at Function._load (module.js:298:12)

    Array.0 (module.js:426:10)

    at EventEmitter._tickCallback (node.js:126:26)

Error Code :

The error.code property is a string label that identifies the kind of error.This is a Hypertext Transfer Protocol response status code.

  • 1xx informational response – the request was received, continuing process
  • 2xx successful – the request was successfully received, understood, and accepted
  • 3xx redirection – further action needs to be taken in order to complete the request
  • 4xx client error – the request contains bad syntax or cannot be fulfilled
  • 5xx server error – the server failed to fulfil an apparently valid request

Conclusion:

It is very important for Ionic mobile app development. Hope you liked the blog. Please share your review in the comment section. See on my next blog./p>

Comments

We Serve clients globally in diverse industries

Stay Upto Date With Our Newsletter.