How to Create RESTful API With Express & Node.js


Hey everyone, In this article I want to show you how to create RESTful API with Express and Node.js. Using Express and Node.js we can create very beautiful RESTful API. But before we move on if you are a beginner you probably new with RESTful API. For the reason that I need to explain what is RESTful API first.

RESTful API

So Let’s understand first what is API?

API

API stands for application program interface (API) that allows two software programs to communicate with each other. Any data can be shared with an application program interface. APIs are implemented by function calls composed of verbs and nouns.

For example, on a real estate website, one API might be used to publish available real estate properties by geography, while a second API provides the visitor with current interest rates and the third API brings in a mortgage calculator. Exposing data with an API can improve the customer experience because it provides greater functionality and scope of services within a single application or other digital property

There are three types of APIs

Private APIs:-

Private APIs, or internal APIs, are published internally for use by the company’s developers to improve its own products and services. These APIs are not exposed to third parties.

Public APIs:-

Public APIs, or open APIs, are published publicly and can be used by any third-party. There are no restrictions on these APIs.

Partner APIs:-

Partner APIs can only be used by specific parties with whom the company agrees to share data. These APIs are used within business relationships, often to integrate software between partnering companies.

Web APIs are designed to represent widely used resources like HTML pages and are accessed using a simple HTTP protocol.  Any web URL activates a web API.  Web APIs are often called REST (representational state transfer) or RESTful because the publisher of REST interfaces doesn’t save any data internally between requests. As such, requests from many users can be intermingled as they would be on the internet.

RESTful API

REST stands for (REpresentational State Transfer). This is an architectural style for developing web services. A primary benefit of using REST, both from a client and server’s perspective, is REST-based interactions happen using constructs that are familiar to anyone who is accustomed to using the internet’s Hypertext Transfer Protocol (HTTP).

REST-based applications can be written using any language, be it Java, Kotlin, .NET, AngularJS or JavaScript. 

There are various HTTP request can use to make RESTful API. The default operation of HTTP is GET, which is intended to be used when getting data from the server. However, HTTP defines a number of other methods, including PUT, POST and DELETE. To exchange data between client and server we are going to use JSON.

 The two most common data exchange formats are JSON and XML, and many RESTful web services can use both formats interchangeably, as long as the client can request the interaction to happen in either XML or JSON.

Now let’s see how to create RESTful API.

Create RESTful API

RESTful APIs enable you to develop any kind of web application having all possible CRUD (create, retrieve, update, delete) operations. To create a restful API we gonna use express framework.

So let’s first understand what is express.

Express

You’re probably aware that JavaScript is the programming language most often used to add interactivity to the front end of a website, but its capabilities go far beyond that—entire sites can be built on JavaScript, extending it from the front to the back end, seamlessly.

Express is a fast, essential and moderate web framework of Node.js.

Express and Node.js gave JavaScript newfound back-end functionality—allowing developers to build software with JavaScript on the server side. Express.js is a Node js web application server framework, which is specifically designed for building single-page, multi-page, and hybrid web applications.

To use express we first need node.js installed in the system. I already installed node.js in my system. If you don’t then install it from nodejs.org website.

Ones you have done that you can now install node packages using npm command. Using npm command we’ll install initialize the project and install various node packages.

So Open your favorite editor and let’s create a new project and initialize it with npm. So I am going to create a new folder on the desktop and named it RESTful. Open RESTful folder in your editor.

Now just initialize your app as node application.

Now install express to create a server.

On the root directory create a new file and named it server.js. In this file create a new server with routes.

server.js

Now your app is started on the port 3000. Just open browser and type http://localhost:3000/todos

In the above code, we had created a get request. So when you open the port 3000 you are going to get hello world response. Now let’s see how this get request works.

Now let’s create our first API endpoint. We before we do that I want to explain what is routing is.

Routing

Routing refers to determining the way in which an application responds to a client request to a particular endpoint.

For example, a client can make a GET, POST, PUT or DELETE HTTP request for various URL’s. Suppose I make a get request on this URL

 http://localhost:3000/Books

If a GET request is made for this URL, then the response should ideally be a list of books. So based on the URL which is accessed, a different functionality on the web server will be invoked and accordingly, the response will be sent to the client. This is the concept of routing.

Each route can have one or more handler functions, which are executed when the route is matched.\

The ‘req’ parameter has information about the request being made

‘res’ parameter which can be used to send information back to the client.

Now just replace the Hello world statement to res.json(db). Now we are going to send the mimic of the database with this API endpoint. 

Let’s create a new folder on the root directory and named it db. Create a db.js file in that folder.

db.js

Now to check this get request open browser on the port 3000. But this is not the best technique to test API. To test your API endpoint we need a tool that tests API endpoint.

So to solve this problem we have postman.

Postman

API Testing Tools. …Postman is a Google Chrome application for testing API calls. A postman is a powerful tool used to test web services. It was developed for sending HTTP requests in a simple and quick way.

You can download Postman at https://www.getpostman.com/.

So just download it and install in the system. Ones you have done that Open it and make a get request to the API endpoint. So just select get and put the request URL. Click on the send to get the response from the API testing tool. That’s it.

Now let’s create a new route with the post request.

To handle HTTP POST request in Express.js version 4 and above, you need to install middleware module called body-parser. body-parser extract the entire body portion of an incoming request stream and exposes it on req.body.

The middleware was a part of Express.js earlier but now you have to install it separately.

This body-parser module parses the JSON, buffer, string, and URL encoded data submitted using the HTTP POST request.

So in short, we use body-parser to submit data with the post request. Install body-parser using NPM as shown below

Ones you have installed body-parser put this code in the server.js file to make a post request.

So as you can see using body parser I am going to pass data with two properties. title and description. We are going to send the response with JSON data.

server.js looks like this:

Just call this file on port 3000. So just type http://localhost:3000. To test API use Postman API Testing Tool.

Send the post request using postman and you will get a response of JSON data.

So using restful API you share resources with a different application. You are not limited to send just get and post request you can send put, delete, patch and header request as well.

If you have any question ask me any time. Thank you for reading. 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *