REST (REpresentational State Transfer) has become the modern standard for building scalable web services. It is fast replacing older alternatives such as SOAP (Simple Object Access Protocol) and WSDL (Web Services Description Language). RESTful APIs have earned a widespread acceptance across the Internet because of their simplicity, performance, and maintainability.
On the other hand, ExpressJS is one of the most popular web servers for NodeJS. It comes with support for building RESTful APIs over HTTP and JSON out-of-the-box. ExpressJS not only provides endpoints for APIs, but is also suitable for building single-page, multi-page, and hybrid applications.
Finally, using NodeJS as an API platform comes with many advantages thanks to its non-blocking, event-driven I/O paradigm. Those features make it suitable for building realtime applications that scale well. NodeJS and SocketIO facilitate developers in moving from the traditional, stateless, one-way connection applications to have realtime, two-way connection web applications. The server and clients can initiate communication asynchronously and exchange data instantly. The server can push data to the client as soon as it is available. This is in contrast to the typical applications, where only the clients can initiate connections and have to poll the servers periodically for any new information.
Without further ado, let's cover the following topics in this chapter:
REST is a stateless, cacheable, and uniform interface that provides client-server communication. It leverages the HTTP protocol. REST uses the HTTP verb methods such as GET, POST, PUT, PATCH, and DELETE. These methods are accompanied by a URI (Uniform Resource Identifier), which has a protocol, domain, and a path. The media type is also specified in the header of the HTTP request, such as HTML, JSON, XML, Images, and Atom to name a few. For our case, we are going to be using only JSON.
The following table shows an example of our future RESTful API for products:
URI |
GET |
PUT/PATCH |
POST |
DELETE |
---|---|---|---|---|
|
Get all the products |
N/A |
Creates new product |
N/A |
|
Get single product |
Update product |
N/A |
Delete product |
The GET method is considered safe or nullipotent since it does not have any side effects on the data (it just reads the data). The PUT and DELETE methods are considered idempotent, since their call produces the same results no matter how many times they are called. The POST method is neither nullipotent nor idempotent because it creates new data every time it is called, and every POST request produces changes in the data. Notice that all the bulk update (PUT) and deletions (DELETE) are not implemented, since they are considered unsafe when modifying more than one resource. More practical examples will be given in later sections of this chapter.
3.144.230.82