Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Creating RESTful APIs With JEC — Part 5: Advanced Concepts

DZone's Guide to

Creating RESTful APIs With JEC — Part 5: Advanced Concepts

This series on RESTful APIs for microservices ends with a tutorial on the JARS API and advanced features.

· Microservices Zone ·
Free Resource

Learn why microservices are breaking traditional APM tools that were built for monoliths.

This article is the last of a series of five focusing on building RESTful APIs over Node.js by using the “JavaScript Enterprise Container” (JEC) specification and its default implementation: GlassCat application server.

In the previous article, we showed how to test JEC RESTful services by using the “JavaScript Unit Testing API” (JUTA) and the different mock APIs. In this article, we come back to the JARS API and explain advanced features to create more complex RESTful applications.

Prerequisites

In order to follow this tutorial, we need to install a GlassCat server instance and deploy the last version of the project, available on GitHub.

You also should read the preceding articles of the series.

JARS and CRUD

REST has been designed on top of the HTTP specification. Regarding the HTTP verbs constructs, we can easily understand that REST is fundamentally adapted to build CRUD APIs. From this point of view, the JARS specification has been thought to keep CRUD integration as simpler as possible.

In preceding articles, we focused on the way to access data (Read). So, in the following sections will take a look at the others CRUD actions: creation, update, and deletion of an item.

Moreover, we address query string structures, which are useful, for example, to implement search engines.

Creating New Items

Creation of new items with REST services can follow different rules, depending on architect preferences and infrastructure constraints. Herein, we will just request the server to create a new item and return its identifier. To do that, we just have to invoke the resource URI with a POST method. JARS uses the @POST decorator to treat such an HTTP call, as shown below:

@POST()
public createUser(@Exit exit:Function):void {
  this.dao.createUser((id: number, err:UsersException)=>{
    exit(id, err, this.getErrorCode(err) || HttpStatusCode.CREATED);
  });
}

Updating Items

Since we use the HTTP POST method to create items in a database-driven CRUD approach, we logically use the PUT method to update each item that belongs to the resource. In that case, we generally use the HTTP method body to access the new version of the updated item.

JARS provides a @RequestBody decorator to allow developers to access body content. So, body content is simply passed as a parameter of the JARS method:

@PUT({
  route: "/:userId"
})
public updateUser(@Exit exit:Function, @PathParam userId:string, @RequestBody body:any):void {
  this.dao.updateUser(userId:number, body:any, (err:UsersException)=>{
    exit(null, err, this.getErrorCode(err) || HttpStatusCode.NO_CONTENT);
  });
}

Deleting Items

Deleting items with JARS is quite as simple as accessing them. We have to use the @DELETE decorator, which responds to an HTTP DELETE method:

@DELETE({
  route: "/:userId"
})
public deleteUser(@Exit exit:Function, @PathParam userId:string):void {
  this.dao.deleteUser (userId:number, (err:UsersException)=>{
    exit(null, err, this.getErrorCode(err) || HttpStatusCode.NO_CONTENT);
  });
}

HTTP Method Parameters

JARS provides metadata to map each HTTP verb to a method in the resource class. All of these metadata accept an object of the type of HttpMethodParams, which allows us to specify additional behaviors implemented by the JEC server.

In the third article of this series, we saw that we can use the route property to specify sub-route parameters for a resource path. The HttpMethodParams interface defines three other properties: consumes, produces and crossDomainPolicy.

These parameters are shortens that directly deal with the HTTP response header parameters:

  • consumes: is used to specify which MIME media types of representations a resource can accept
  • produces: is used to specify the MIME media types or representations a resource can produce and send back to the client
  • crossDomainPolicy: is used to allow cross-domain access

The following sample code shows how to set the JSON MIME media types for a basic HTTP request:

@GET({
  produces: “application/json”
})
public getUsers(@Exit exit:Function):void {
  this.dao.getUsers((data: any, err:UsersException)=>{
    exit(data, err, this.getErrorCode(err));
  });
}

Working With Query Parameters

Once we have manipulated items from the data store, we might need to apply non-CRUD complex operations over it. HTTP query parameters provide a powerful way to perform such operations.

JARS tries to make query parameters as easy-to-use as possible. Like path parameters, query parameters are declared as method parameters, by using the @QueryParam decorator:

@GET({
  route: "/search"
})
public findUser(@QueryParam token:string, @Exit exit:Function):void {
   this.dao.findUser (token, (user:UserV3, err:any)=> {
    exit(user, err);
  });
}

You can declare as many query parameters as you want, which will be identified by their string value. So, the preceding sample code must be invoked with the URI below:

[http://www.my-domain.com/my-api]/users/search?token=roger

Accessing Cookies

Since REST is stateless by definition, developer might want to access data stored in cookies, for example to emulate a session mechanism. There too, JARS comes with a specific decorator, @CookieParam, which works on the same model as @QueryParam:

@GET({
  route: "/token"
})
public getUserJwt (@CookieParam userJwt:string, @Exit exit:Function):void {
  console.log(userJwt);
  exit(userJwt);
}

In the preceding code sample,  userJwt refers to the name of the cookie parameter we want to retrieve.

Microservices Development

Contrary to Spring Boot, the design of JEC makes it highly efficient during development steps, especially in local environments. JEC specifies that:

"Each Domain Container is associated with one HTTP Task. HTTP Tasks can be used to serve multiple domains, but a good practice is to associate only one Domain Container per HTTP Task."

JEC Domains Architecture

The main aspect of this structure turns around JEC connectors which ensures strict partitioning between all services. Thanks to this design, the developer can start and stop all of its microservices at once. This concept is particularly adapted to modern deployment architectures, where you can associate one JEC domain to a single code repository and deploy it into a specific container.

Summary

In this article series, Creating RESTful APIs with JEC, we have discussed how to use the JavaScript API for REST Services (JARS) to easily create microservices based on REST principles.

JARS takes benefits of its model, JAX-RS, to provide the developer a well-designed solution in terms of separation of concerns and modularity.

Moreover, the core integration of the API versioning is a great improvement to solve scalability issues of REST services.

In our next article, we will demonstrate the interest of using JEC to create experimental annotation-based frameworks. Particularly, we will try to solve adaptive design concerns, by simplifying the declaration and the access regarding media assets.

Acknowledgements

I would like to thank people who have checked these articles, Jeremy G. and his wife, Jeremie B. Ph. D. (and his wife), Romain, and of course, moderators for some subtle modifications.

Record growth in microservices is disrupting the operational landscape. Read the Global Microservices Trends report to learn more.

Topics:
rest api ,javascript ,integration ,tutorial ,microservices ,apache apis ,node.js

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}