- Lab
-
Libraries: If you want this lab, consider one of these libraries.
- Core Tech
Guided: Implementing RESTful Communication Between Node.js Microservices
Unlock the power of microservices with this hands-on Guided Lab focused on building RESTful APIs using Node.js. Dive into the essentials of service architecture, learn to design seamless interactions, and master implementing robust, scalable communication strategies with Express. This guided lab is perfect for developers looking to enhance their API expertise and microservices design.
Lab Info
Table of Contents
-
Challenge
Introduction
Welcome to the Guided: Implementing RESTful Communication Between Node.js Microservices Code Lab! In this lab, you will learn how to implement RESFTful communication between Node.js microservices. Before you dive in, take a look at some fundamental concepts:
-
Node.js is a cross-platform JavaScript runtime environment that you can use to create servers, microservices, web apps, command line tools and scripts. Node.js is free and open source.
-
A microservice is an architectural style of creating an application that structures the app as a collection of services focused on specific business capabilities, which are decoupled and can be deployed independently from one another.
-
A RESTful API is an interface that more than one application or system uses to exchange information securely over the internet.
So, for example, say that you are developing a web application that processes
ordersfor your clients. In this application, in order to process theorders, you'll need to fulfill them with theproductsyour company sells.Therefore, from a business perspective and by using a microservices architecture, you can already identify two key elements to consider:
ordersandproducts.Instead of having one single monolith that processes
ordersandproducts, you can use a microservices architecture approachto create a service (essentially a RESTful API endpoint) that processesorders, and another endpoint that returns information about the company'sproducts.Throughout this lab, you'll explore how to build two microservices: one for processing
ordersand another for retrievingproducts. You'll see one can be used to interact with the other, as RESTful API endpoints.Therefore you'll build two microservices using RESTful communication:
- Product service: Manages product information.
- Order service: Manages orders and communicates with the Product service to retrieve product details.
By following along, you'll understand the basics of microservices architecture, RESTful principles, and inter-service communication. Some familiarity with JavaScript and REST is beneficial, although not required.
You will write the code for this project under the
srcfolder, where you'll find theproduct-serviceandorder-servicesubfolders.Within the
product-servicesubfolder, you'll find aserver.jsfile, where you will write the code for theproductsmicroservice.Within the
order-servicesubfolder, you'll find aserver.jsfile, where you will write the code for theordersmicroservice.To create the RESTful API that will allow the communication between both microservices, you'll use Express.js. Express.js is a small framework for building RESTful APIs with Node.js.
info> The solution for each step in this lab are available for your reference in the
solutiondirectory.
Each step might have one or more tasks. For example, the solution for Step 2 - Task 1 can be found in thestep02_task01.jsfile.
Within thesolution/product-service/server.jsfile, you'll find the final code for theproductsmicroservice.
Within thesolution/order-service/server.jsfile, you'll find the final code for theordersmicroservice.
By default, when this lab opens, you'll see two tabs, both calledserver.js.
The firstserver.jsfile corresponds to theproduct-service, whereas the secondserver.jsfile corresponds to theorder-service. -
-
Challenge
Creating the Product Service
You will create the
product-servicein the firstserver.jsfile tab.info> Alternatively, you can navigate to the
src/product-servicefolder and open theserver.jsfile.In this step, you will create the foundation for the
product-service, which is a fundamental part of the whole solution.Write the necessary code to initialize the
product-serviceby completing the following: -
Challenge
Fetching All Products
Now that you have initialized the
product-service, it's time to create a list of products and retrieve it.Your next objective is to fetch all the
productsfrom a product list. You have created a list ofproducts. Create a route that listens forGETrequests at the/productsendpoint.When a request is received by the
product-serviceat this endpoint, it will respond with theproductsdata. -
Challenge
Fetch a Single Product by the Id
Now that you know how to retrieve all products, it's time to fetch a single product by
id.You created the following endpoint that is used for fetching a single product by
id.app.get('/products/:id', (req, res) => { }); ``` Now that you have managed to retrieve a product by a specific ```id```: -
Challenge
Running the Product Service
Well done for getting here!
By now, you have managed to write code for the
product-servicethat fetch all products, and fetch a single product byid.There's just one remaining step to to finish creating the
product-serviceand that is to start the server on port3000. To start theproduct-service: -
Challenge
Creating the Order Service
With the
product-servicecreated, it's now time to create theorder-service.Within the
solution/order-servicefolder, open theserver.jsfile.The
server.jsfile contains the following code:// The order-service - leave this line as is const express = require('express'); const axios = require('axios'); const app = express(); const PORT = 3001; app.use(express.json());This code imports the Express.js framework, and also the Axios library, which is used for making HTTP(S) calls.
This code also create an
expressinstance, and set thePORTvalue to3001.By invoking
app.use(express.json()), all responses are returned as JSON.So, to make the
order-servicework, you must create an/orderPOSTendpoint which will be used for invoking the product service to fetch product details. To create thePOSTendpoint for theorder-service. -
Challenge
Call the Product Service
Now that you have created the
order-service, you must add additional code to the/orderendpoint that can invoke theproduct-serviceto fetch product details. Within theorder-service, just after theconst { data: product } = await axios.getline: The final task you must complete is to start theorder-service. -
Challenge
Testing with CURL
Well done for reaching this point of the lab!
In this final step, you are going to run and test both microservices. You'll notice that there are three Terminal tabs open.
1. Go to the first Terminal tab and run the
product-serviceby executing the following command:node src/product-service/server.js2. Using the second Terminal tab, run the
order-serviceby executing the following command:node src/order-service/server.jsAt this stage, both microservices will be running.
3. Using the third Terminal tab, fetch all the products from the
product-serviceby executing the following command:curl http://localhost:3000/productsThis will return the list of products.
4. To highlight how both microservices can work together, create an
orderby executing the following command in the third Terminal tab:curl -X POST http://localhost:3001/order -H "Content-Type: application/json" -d '{"productId": 1, "quantity": 4}'Once you execute this command, you'll see the following result:
{"product":"Laptop","price":1000,"quantity":4,"total":4000}By doing this, you have seen how both services can communicate with each other.
In this example, you invoked the
order-serviceto create anorder, which theorder-servicedoes by fetching a specific product that is passed to theorder-serviceas aPOSTpayload:-H "Content-Type: application/json" -d '{"productId": 1, "quantity": 2}'Now you have gained the basic knowledge of creating and working with Node.js microservices using Express.js for RESTful communication.
About the author
Real skill practice before real-world application
Hands-on Labs are real environments created by industry experts to help you learn. These environments help you gain knowledge and experience, practice without compromising your system, test without risk, destroy without fear, and let you learn from your mistakes. Hands-on Labs: practice your skills before delivering in the real world.
Learn by doing
Engage hands-on with the tools and technologies you’re learning. You pick the skill, we provide the credentials and environment.
Follow your guide
All labs have detailed instructions and objectives, guiding you through the learning process and ensuring you understand every step.
Turn time into mastery
On average, you retain 75% more of your learning if you take time to practice. Hands-on labs set you up for success to make those skills stick.