HOW TO BUILD A REST API WITH KOA.JS

Mishan Kavindu Perera
8 min readMay 15, 2022

RESTful Services

REST which stands for REpresentational State Transfer, is used to work efficiently on the Web. It is a style of architecture, and it is not a type of protocol. It specifies constraints, one of which can be taken as a uniform interface. In REST, the resources named as data and functionality are being accessed using Uniform Resource Identifiers or else (URIs), the links on the Web. These resources use operations which are well-defined and straightforward. REST use HTTP, which is a stateless communication protocol which is being designed as a client/server architecture. In its architecture, representations of resources are exchanged by clients and servers by using a standardized interface and protocol. RESTful web services are platform-independent, which can be written using any programming language & can be executed on any platform. Also, it consumes less bandwidth and resources. RESTful web services Permit different data formats like Plain Text, HTML, XML and JSON.

RESTful applications have become simple, lightweight, and fast due to the below reasons.

Identifying Resources through URI: A RESTful web service has a set of resources which identify the interaction targets with its clients. URLs identify these resources, providing a global addressing space for resource and service discovery.

• Uniform interface: PUT, GET, POST, and DELETE are the only four operations that can be used to create, read, update, or delete resources. PUT generates a new resource that can then be deleted using DELETE. The GET method retrieves the current status of a resource in some form. POST updates the status of a resource.

Resources are detached from their representation, allowing their content to be accessible in various formats, including HTML, XML, plain text, PDF, JPEG, JSON, etc. The resource’s metadata is available and can be used to control caching, identify transmission faults, negotiate the best representation format, and perform authentication or access control, among other things.

Stateful hyperlink interactions: Every interaction with a resource is stateless; request messages are self-contained. The principle of direct state transfer underpins stateful interactions. The several methods of exchanging states, including URI rewriting, cookies, and hidden form fields.

HTTP Messages

Messaging is the name for this method. HTTP protocols are used by RESTful Web Services to communicate between client and server. A client sends a message to the server in an HTTP Request, and the server answers with an HTTP Response. These messages include message data and metadata or information about the message. Let’s have a look at the HTTP Request and HTTP Response messages:

HTTP Request

There are five major components to an HTTP request.

  1. Verb identifies HTTP methods like GET, POST, DELETE, and PUT.

2. URI (Uniform Resource Identifier) identifies the server’s resource. This field indicates the HTTP version. Consider HTTP version 1.1.

3. The metadata of the HTTP Request message is stored as key-value pairs in the Request Header.

4. Client (or browser) type, the format supported by the client, message content format, cache settings, etc.

5. Message content or Resource representation in the Request Body.

There are four primary components to an HTTP response.

  1. The Status/Response Code indicates the Server status for the requested resource. For example, 404 indicates that a resource was not found, and 200 indicates that the response was OK.

2. This field indicates the HTTP version. Consider HTTP v1.1.

3. Metadata for the HTTP Response message is stored as key-value pairs in the Response Header. For instance, content length, type, response date, server type, etc.

4. Response Body Content of the response message or Resource representation.

HTTP Verbs

1. Method of HTTP GET

Use GET requests exclusively to get resource representations/information, not change it. GET requests are considered safe because they do not modify the resource’s state. Furthermore, GET APIs should be idempotent, which implies that making repeated identical queries should always return the same response until another API (POST or PUT) changes the resource’s state on the server.

GET returns a JSON or XML representation and the HTTP status code 200 if the address is successfully received (error-free) (OK). The error code 404 (NOT FOUND) or 400 (BAD REQUEST) is returned in most cases.

Example for GET request URI:

http://www.usermanagement/api/users/{username}/posts - Get posts created by user

2. POST Method on HTTP

The HTTP POST request is most typically used to generate new resources. POST methods are used to add a new resource to the collection of resources when speaking strictly in terms of REST.

An HTTP code 201 is returned upon successful creation, along with the address of the newly created resource in the ‘Location’ header.

Examples for HTTP POST requests:

http://www.domain/api/posts - Create Post

http://www.domain/api/posts/{postId}/comments - Create new comment for post with id = postId

3. PUT Method on HTTP

PUT APIs are mainly used to update existing resources (if the resource does not exist, then API may decide to create a new resource or not). The origin server MUST inform the user agent via the HTTP response code 201 (Created) if the PUT API has created a new resource. If an existing resource has been modified, either the 200 (OK) or 204 (No Content) response codes SHOULD be sent to indicate successful completion of the request.

Examples for HTTP PUT requests:

http://www.domain/api/posts/{id} - Update post by id

http://www.domain/api/posts/{postId}/comments/{id} - Update comment by id if it belongs to post with id = postId

The difference between the POST and PUT APIs can be observed in request URIs. POST requests are made on resource collections, whereas PUT requests are made on a single resource.

4. DELETE Method in HTTP

Use the DELETE APIs (identified by the Request-URI) to delete resources.

HTTP response code 200 (OK) if the response includes an entity specifying the status, 202 (Accepted) if the action has been queued, or 204 (No Content) if the action has been completed, but the response does not include an entity.

Example for HTTP DELETE request:

http://www.domain/api/posts/{id} - Delete post

5. PATCH HTTP Method

PATCH requests are used to make incremental changes to a resource. To be clear, PUT requests also affect a resource object, so the PATCH method is the ideal choice for partially changing an existing resource, and PUT should only be used if you’re completely replacing a resource.

Constraints

1. Client-Server

The client and server are kept loosely linked by this requirement. In this situation, the client is unconcerned about the server’s implementation details, and the server is unconcerned about the client’s use of the data. A common interface is maintained between the client and the server to facilitate communication. This restriction is based on the separation of concerns principle.

Separates user interface problems from data storage concerns through separation of concerns.

• Improves interface portability across many platforms.

• Allows components to evolve independently and improves scalability by simplifying server components.

2. Stateless

The service should not be required to store user sessions. To put it another way, the constraint is that the server should not remember the application’s state. As a result, the client should transmit all relevant information with each request because the server cannot reuse data from prior requests because it does not remember it. The message has the all necessary information.

• The session state is retained solely on the client using the statelessness constraint.

• Visibility is improved because a monitoring system only needs to look at one request.

• Reliability is increased since partial failures are easier to recover from.

• Scalability is improved because resources for storing state are not required.

• The server does not need to manage anything.

3. Cacheable

This restriction must be compatible with a caching system. At various levels, the network infrastructure should support a cache. Repeated round trips between the client and the server to retrieve the same resource can be avoided via caching.

By enabling non-shared caching,

• Data in response to a request is cacheable or non-cacheable, either implicitly or explicitly.

• If a response is cacheable, a client cache is granted permission to reuse the response data for future, similar queries.

• Increases efficiency, scalability, and user satisfaction.

• The cacheable limitation lowers reliability.

4. Uniform Interface

This constraint denotes a generic interface that manages all client-server interactions uniformly, simplifying and decoupling the architecture. This constraint specifies that each resource supplied to the client must have a specific address and be accessible via a generic interface. A general collection of methods allows the client to act on the resources.

The entire system design is simplified, and interaction visibility is improved by using uniform interface constraints. Implementations are divorced from the services they deliver, allowing them to evolve independently.

Trade-off: Reduces efficiency because data is delivered in a standard format rather than one tailored to the application’s requirements. A uniform interface contains four sub-constraints as well.

• Resource identification

• Resource manipulation via representations

• Self-descriptive communications

• Hypermedia as an application state engine (HATEOAS)

5. Layered System

For implementation, the server can have numerous layers. By allowing load balancing, this layered architecture aids in scalability. It also boosts performance by distributing shared caches at several levels.

Applying a layered system constraint enhances simplicity by separating concerns, similar to the client-server constraint.

• Legacy services can be encapsulated, and new services can be protected from legacy clients.

• By facilitating load balancing, intermediaries can help improve system scalability.

• Having shared caches at the organizational domain’s edges can benefit considerably. Security policies, such as firewalls can also be enforced.

• Because messages are self-descriptive and their semantics are visible to intermediates, intermediaries can actively modify message content.

Tradeoff: Increases overhead and delay while lowering user perception.

6. Code on Demand

This restriction is not required. This restriction specifies that the client apps’ functionality can be expanded at runtime by enabling the server’s download and execution of code. Applets and JavaScript code are two examples of client-side code sent and performed at runtime.

Using the Code-on-Demand constraint

• Clients are simplified, resulting in less feature coupling.

• Increases scalability by offloading tasks from the server to the clients.

Trade-off: Reduces visibility generated by the code, which is difficult to interpret for an intermediate.

Koa JS

The team behind express developed Koa.js, an open-source Node.js web framework. According to its official website, the framework aspires to provide a smaller, more expressive, and more robust base for web applications and APIs. Koa uses asynchronous functions to reduce the requirement for callbacks and improve error handling. Koa’s core does not include any middleware. It offers an improved set of ways for speeding up and exciting the server-building process.

Features

1. Koa.js is cutting-edge and future-ready — Unlike previous Node.js frameworks, Koa.js is built using ES6, which simplifies the construction of complicated applications by introducing new classes and modules. This aids in the development of maintainable apps.

2. Koa.js makes advantage of ES6 generators to make synchronous programming and control flow easier. These generators can also control code execution on the same stack as functions.

3. In comparison to other Node.js frameworks, Koa.js has a minimal footprint. It allows developers to create middleware that is lighter.

4. Koa.js includes an error catchall to assist prevent website crashes.

5. Koa.js makes use of a context object, which is a container for request and response objects.

Users of Koa.js

For their websites and online APIs, several companies use the Koa.js framework. The following is a list of five well-known companies that use the Koa.js framework.

1. Paralect

2. Pubu

3. Bulb

4. GAPO

5. Clovis

--

--

Mishan Kavindu Perera

Software Engineering Undergraduate of Sri Lanka Institute of Information Technology