<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[CloudOpsCamp]]></title><description><![CDATA[CloudOpsCamp]]></description><link>https://cloudopscamp.com</link><generator>RSS for Node</generator><lastBuildDate>Wed, 08 Apr 2026 20:07:07 GMT</lastBuildDate><atom:link href="https://cloudopscamp.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Hands-on with Docker, Node.js, and Express: Beginner’s guide to getting Started With Containerisation]]></title><description><![CDATA[You may have already heard about docker and how great it is. If you have not you can get your idea from their official site. In short, if you are looking forward to starting a career in DevOps, the first thing you should know and learn about is conta...]]></description><link>https://cloudopscamp.com/hands-on-with-docker-nodejs-and-express-beginners-guide-to-getting-started-with-containerisation</link><guid isPermaLink="true">https://cloudopscamp.com/hands-on-with-docker-nodejs-and-express-beginners-guide-to-getting-started-with-containerisation</guid><category><![CDATA[Docker]]></category><category><![CDATA[Kubernetes]]></category><category><![CDATA[AWS]]></category><category><![CDATA[Azure]]></category><category><![CDATA[REST API]]></category><dc:creator><![CDATA[Humayun Rashid]]></dc:creator><pubDate>Fri, 24 Feb 2023 18:26:44 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1677263594328/45171fec-5523-4011-b159-1689d6f4f4a7.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>You may have already heard about docker and how great it is. If you have not you can get your idea from their <a target="_blank" href="https://www.docker.com/why-docker">official site</a>. In short, if you are looking forward to starting a career in DevOps, the first thing you should know and learn about is containerization. There are several containerization technologies are available, but Docker has become the <strong>de facto</strong> standard to build and share containerized apps. In this story, I am going to tell you how you can make your hands dirty with Docker.</p>
<h1 id="heading-table-of-content"><strong>Table of content</strong></h1>
<ul>
<li><p>The traditional way to run a node app</p>
</li>
<li><p>Dockerizing Node.js app</p>
</li>
</ul>
<h1 id="heading-the-traditional-way-to-run-a-node-app"><strong>The traditional way to run a node app</strong></h1>
<p>It is not required to know to code to get started with Docker. But you need to know how to run the application that you are intending to dockerize. Let’s consider one of the node apps that I build during learning node.js and express. Before jumping into Docker, I would like to show you how you can run this node app in your local machine. The steps are:</p>
<ul>
<li><p><strong>Step 1:</strong> Install git</p>
</li>
<li><p><strong>Step 2:</strong> Install Node and NPM</p>
</li>
<li><p><strong>Step 3:</strong> Clone Git repository</p>
</li>
<li><p><strong>Step 4:</strong> Run web app</p>
</li>
</ul>
<h2 id="heading-step-1-install-git"><strong>Step 1: Install Git</strong></h2>
<p>You will find great guidelines from <a target="_blank" href="https://www.linode.com/docs/development/version-control/how-to-install-git-on-linux-mac-and-windows/">here</a> about installing git for your local machine ( Linux, Mac, or Windows).</p>
<h2 id="heading-step-2-install-nodejs-and-npm"><strong>Step 2: Install Nodejs and NPM</strong></h2>
<p>Download and install node.js from the <a target="_blank" href="https://nodejs.org/en/download/">official site</a>. Versions should be at least 10 or higher 10. Once you are done, open a terminal, and verify the installation:</p>
<pre><code class="lang-javascript">$ node -v
$ npm -v
</code></pre>
<h2 id="heading-step-3-clone-the-git-repository"><strong>Step 3: Clone the git repository</strong></h2>
<p>Open your terminal or PowerShell. Run down the following command to clone the git repository.</p>
<pre><code class="lang-javascript">$ git clone https:<span class="hljs-comment">//github.com/humayun-rashid/covid-19-node-app.git</span>
</code></pre>
<h2 id="heading-step-4-run-the-web-app"><strong>Step 4: Run the web app</strong></h2>
<p>Let’s install our npm dependencies that are listed in package.json. You will find the package file in the repository. Run the following command in your terminal to install the dependencies.</p>
<pre><code class="lang-javascript">$ npm install
</code></pre>
<p>Once you are done with the dependencies installation, the app can be started with the following line of command and you can see that the server will start running in port 3000.</p>
<pre><code class="lang-javascript">$ node server.jsServer is running <span class="hljs-keyword">in</span> port <span class="hljs-number">3000</span>
</code></pre>
<p>Open your favourite browser and visit the following link to access the application.</p>
<pre><code class="lang-javascript">http:<span class="hljs-comment">//localhost:3000</span>
</code></pre>
<p>You should see something like the following:</p>
<p><img src="https://miro.medium.com/max/1260/1*NXyxGoCBX6Uk-ua-mg4TnA.png" alt /></p>
<p>Write down some country’s name and it should give output. To stop the server, you need to press <code>ctrl + c</code>.</p>
<h1 id="heading-dockerizing-nodejs-app"><strong>Dockerizing Node.js app</strong></h1>
<p>The steps to create an image and push it to a registry using docker are listed below:</p>
<ul>
<li><p><strong>Step 1:</strong> Install Docker</p>
</li>
<li><p><strong>Step 2:</strong> Create Dockerfile</p>
</li>
<li><p><strong>Step 3:</strong> Build and run the image</p>
</li>
<li><p><strong>Step 4:</strong> Tag an image and push it to the registry</p>
</li>
<li><p><strong>Step 5:</strong> Stop the container and cleanup</p>
</li>
</ul>
<h2 id="heading-step-1-install-docker"><strong>Step 1: Install Docker</strong></h2>
<p>I will recommend installing a docker desktop for Mac and Windows users from <a target="_blank" href="https://docs.docker.com/get-docker/">here</a>. Ubuntu users can run the following commands to install Docker.</p>
<pre><code class="lang-bash">$ sudo apt-get update
$ sudo apt-get remove docker docker-engine docker.io
$ sudo apt install docker.io
$ sudo systemctl start docker
$ sudo systemctl <span class="hljs-built_in">enable</span> docker
</code></pre>
<p>You should test if the docker is working fine after installation. Open your terminal and run the following command:</p>
<pre><code class="lang-bash">$ docker --version
$ docker run hello-word
</code></pre>
<p>I also run a base image and echo a message to verify if the docker is functioning properly.</p>
<pre><code class="lang-bash">$ docker run alpine:latest <span class="hljs-string">"echo"</span> <span class="hljs-string">"Hello, World"</span>
</code></pre>
<h2 id="heading-step-2-create-dockerfile"><strong>Step 2: Create Dockerfile</strong></h2>
<p>Create a file in the same directory named “Dockerfile” without any extension. I am using <a target="_blank" href="https://code.visualstudio.com/">Visual Studio Code</a> to edit my Dockerfile. If you are in Ubuntu or Mac, you can create a new Docker configuration file from the terminal within the same directory by running:</p>
<pre><code class="lang-bash">$ touch Dockerfile
</code></pre>
<p>Add the following configuration first, It might not make any sense right now if you are new to this but I am going to explain what’s happening here later.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Base Image</span>
FROM node:10<span class="hljs-comment"># Create app directory</span>
WORKDIR /usr/src/app<span class="hljs-comment"># Install app dependencies</span>
COPY package*.json ./<span class="hljs-comment"># Install dependencies</span>
RUN npm install<span class="hljs-comment"># Bundle app source</span>
COPY . .<span class="hljs-comment">#Expose port to 3000</span>
EXPOSE 3000<span class="hljs-comment"># Add command to run</span>
CMD [ <span class="hljs-string">"node"</span>, <span class="hljs-string">"server.js"</span> ]
</code></pre>
<p><strong>Base Image:</strong> The first line defines a base image that we are going to use to build our app. We have chosen a base image that has already node and npm, so we don’t need to install it additionally.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Base Image</span>
FROM node:10
</code></pre>
<p><strong>Work directly:</strong> The next line is for creating a working directory for our app in the base image.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Create app directory</span>
WORKDIR /usr/src/app
</code></pre>
<p><strong>Dependency install:</strong> In the next step, app dependencies will be installed. First, the package.json file will be copied to the directory, and then the npm install command will be executed to install essential packages.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Install app dependencies</span>
COPY package*.json ./<span class="hljs-comment"># Install dependencies</span>
RUN npm install
</code></pre>
<p><strong>Copy to work directory:</strong> In the next step, <code>COPY</code> will be used to copy all the content of the app directory to the container’s working directory.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># Bundle app source</span>
COPY . .
</code></pre>
<p><strong>Port expose:</strong> The app needs to be exposed to the port <code>3000</code> using the <code>EXPOSE</code> instruction.</p>
<pre><code class="lang-bash">EXPOSE 3000
</code></pre>
<p><strong>Command:</strong> To start our server <code>CMD</code> will be used. Commands need to be separated by a comma.</p>
<pre><code class="lang-bash">CMD [ <span class="hljs-string">"node"</span>, <span class="hljs-string">"server.js"</span> ]
</code></pre>
<h2 id="heading-step-3-build-and-run-the-image"><strong>Step 3: Build and run the image</strong></h2>
<p>Once Dockerfile is written and placed in the same directory, the following command can build the image.</p>
<pre><code class="lang-bash">$ docker build -t covid-19:latest .
</code></pre>
<p>Now, run the following command to check if the image has been created properly.</p>
<pre><code class="lang-bash">$ docker images
</code></pre>
<p>It should list all the images. To run the image, use the following command.</p>
<pre><code class="lang-bash">$ docker run --rm --name covid-19 -it -p 3000:3000 covid-19:latest
</code></pre>
<p><code>--rm</code>: The container is removed when it exits or when the daemon exits.</p>
<p><code>--name</code>: Define a name for the container. If it is not used, then the daemon generates a random string name.</p>
<p><code>-it</code>: To be able to do interactive processes (e.g. bash/shell)</p>
<p><code>-p</code>: It is used for port forwarding.</p>
<p>Now, open your browser and visit <a target="_blank" href="HTTP://localhost:3000"><code>HTTP://localhost:3000</code></a> and you should see that your app is running.</p>
<h2 id="heading-stop-the-container"><strong>Stop the container</strong></h2>
<p>You can not stop a container by pressing <code>ctrl + c</code>c from the same terminal. To stop a running container, you need to first open a new terminal and then run the following command to get the container ID.</p>
<pre><code class="lang-bash">docker ps
</code></pre>
<p>Now perform the following docker stop command with container ID to stop the running container.</p>
<pre><code class="lang-bash">docker stop [ID]
</code></pre>
<h2 id="heading-run-in-detached-mode"><strong>Run in detached mode</strong></h2>
<p>The container we were running previously was running in the attached mode. To start a container in detached mode, we need to provide <code>-d</code> . Run the following command, and you will notice that the container has started in detached mode.</p>
<pre><code class="lang-bash">$ docker run --rm --name covid-19 -d -it -p 3000:3000 covid-19:latest
</code></pre>
<p>If you want to attach again, list the running container, and run the command attach with your container name.</p>
<pre><code class="lang-bash">docker container ls
docker container attach covid-19
</code></pre>
<h2 id="heading-bash-shell-in-a-terminal"><strong>Bash shell in a terminal</strong></h2>
<p>To start using a bash shell inside of the container, the following command needs to be performed.</p>
<pre><code class="lang-bash">docker <span class="hljs-built_in">exec</span> --rm --name covid-19 -it -p 3000:3000 covid-19:latest /bin/bash
</code></pre>
<ul>
<li>Another approach is to use the command at the end. The following command will list down all the files inside the container.</li>
</ul>
<pre><code class="lang-bash">docker <span class="hljs-built_in">exec</span> --rm --name covid-19 -it -p 3000:3000 covid-19:latest ls
</code></pre>
<h2 id="heading-step-4-tag-an-image-and-push-to-the-registry"><strong>Step 4: Tag an image and push to the registry</strong></h2>
<p>To push the image to the Docker registry, you need to create an account for the docker registry <a target="_blank" href="https://hub.docker.com/_/registry">here</a>. First, tag the image with the repository name and then push it using the following commands:</p>
<pre><code class="lang-bash">docker tag covid-19:latest (repo-name)/covid-19:latest
docker push (repo-name)/covid-19:latest
</code></pre>
<h1 id="heading-step-5-cleanup"><strong>Step 5: Cleanup</strong></h1>
<p>To delete the image, first list all the images with image ID. Then use <code>rmi</code> the command with image ID to remove the image. You can use <code>-f</code> in the case of force image removal is needed.</p>
<pre><code class="lang-bash">$ docker imagesREPOSITORY                TAG                 IMAGE ID            CREATED             SIZE
test1                     latest              fd484f19954f        23 seconds ago      7 B (virtual 4.964 MB)
<span class="hljs-built_in">test</span>                      latest              fd484f19954f        23 seconds ago      7 B (virtual 4.964 MB)
test2                     latest              fd484f19954f        23 seconds ago      7 B (virtual 4.964 MB)$ docker rmi fd484f19954f
</code></pre>
<h2 id="heading-clean-up-all-resources"><strong>Clean up all resources</strong></h2>
<p>It is possible to clean up all dangling resources (images, containers, volumes, and networks ) with one single command. Flag <code>-a</code> can be added to remove stopped containers and all unused images.</p>
<pre><code class="lang-bash">$ docker system prune
$ docker system prune -a
</code></pre>
]]></content:encoded></item><item><title><![CDATA[RESTful API development with Node.js and Express: Getting started with coding ( Part — 2)]]></title><description><![CDATA[This is the second part of RESTful API development with Node.js and Express. I hope you already have gone through the first part and created your project environment. If you have not read the first part, you can check it here. In this part, we are go...]]></description><link>https://cloudopscamp.com/restful-api-development-with-nodejs-and-express-getting-started-with-coding-part-2</link><guid isPermaLink="true">https://cloudopscamp.com/restful-api-development-with-nodejs-and-express-getting-started-with-coding-part-2</guid><category><![CDATA[REST API]]></category><category><![CDATA[AWS]]></category><dc:creator><![CDATA[Humayun Rashid]]></dc:creator><pubDate>Fri, 03 Feb 2023 20:45:26 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1677264179077/e221ebed-9a86-4eb1-8903-d44e9050f2f7.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This is the second part of RESTful API development with Node.js and Express. I hope you already have gone through the first part and created your project environment. If you have not read the first part, you can check it here. In this part, we are going to get started building our RESTful API. You will find all the codes from Github:</p>
<pre><code class="lang-plaintext">https://github.com/humayun-rashid/first-rest-api-medium.git
</code></pre>
<pre><code class="lang-plaintext">https://github.com/humayun-rashid/first-rest-api-medium.git
</code></pre>
<p>We will start by creating a new directory with a preferred name. In my case, I am naming it “first-rest-API”. Open the terminal and type the following command to create a new directory and navigate to the newly-created directory.</p>
<pre><code class="lang-bash">$ sudo mkdir rest-API-project
$ <span class="hljs-built_in">cd</span> rest-API-project
</code></pre>
<p>After navigating to the directory, you can open visual studio code by writing the following command to your directory.</p>
<pre><code class="lang-bash">$ code .
</code></pre>
<p>Alternatively, you can create a repository in GitHub with your preferred project name such as “first-rest-api”. If you have already installed git by following the previous article, you should be able to clone the repository by the following command.</p>
<pre><code class="lang-bash">$ git <span class="hljs-built_in">clone</span> <span class="hljs-string">"git repo url"</span>
</code></pre>
<p>Then navigate to the directory and start visual studio code by running the following command.</p>
<pre><code class="lang-bash">$ <span class="hljs-built_in">cd</span> rest-API-project
$ code .
</code></pre>
<h2 id="heading-generate-packagejson-by-npm-init"><strong>Generate Package.json by NPM init</strong></h2>
<p>We will now start developing our RESTful API by generating the “package.json” file which is going to contain all the dependencies. This file will be updated when adding further dependencies during the development process. To generate “package.json”, run the following command in the terminal that will request some answers to questions to generate the file. To autofill, the question, “-y” can be added at the end of the command.</p>
<pre><code class="lang-bash">$ npm init
$ npm init -y
</code></pre>
<p>A “package.json” file will be created similar to the following in the project’s root directory.</p>
<pre><code class="lang-bash">{
  <span class="hljs-string">"name"</span>: <span class="hljs-string">"first-rest-api-medium"</span>,
  <span class="hljs-string">"version"</span>: <span class="hljs-string">"1.0.0"</span>,
  <span class="hljs-string">"description"</span>: <span class="hljs-string">""</span>,
  <span class="hljs-string">"main"</span>: <span class="hljs-string">"index.js"</span>,
  <span class="hljs-string">"scripts"</span>: {
    <span class="hljs-string">"test"</span>: <span class="hljs-string">"echo \"Error: no test specified\" &amp;&amp; exit 1"</span>
  },
  <span class="hljs-string">"repository"</span>: {
    <span class="hljs-string">"type"</span>: <span class="hljs-string">"git"</span>,
    <span class="hljs-string">"url"</span>: <span class="hljs-string">"git+https://github.com/humayun-rashid/first-rest-api-medium.git"</span>
  },
  <span class="hljs-string">"keywords"</span>: [],
  <span class="hljs-string">"author"</span>: <span class="hljs-string">""</span>,
  <span class="hljs-string">"license"</span>: <span class="hljs-string">"ISC"</span>,
  <span class="hljs-string">"bugs"</span>: {
    <span class="hljs-string">"url"</span>: <span class="hljs-string">"https://github.com/humayun-rashid/first-rest-api-medium/issues"</span>
  },
  <span class="hljs-string">"homepage"</span>: <span class="hljs-string">"https://github.com/humayun-rashid/first-rest-api-medium#readme"</span>
}
</code></pre>
<h2 id="heading-install-express-framework-and-nodemon"><strong>Install Express Framework and Nodemon</strong></h2>
<p>for the next step, we are required to install Express to our project directory as well as save it in the dependencies list of “package.json”. The dependency can also be saved as “development dependency” in case it is required to be used only for development. The purpose of installing dependency as a development dependency is that package users will not be required to install it in production.</p>
<pre><code class="lang-bash">$ npm install express — save
</code></pre>
<p>To install Express temporarily and not add it to the dependencies list:</p>
<pre><code class="lang-bash">$ npm install express — no-save
</code></pre>
<p>Now, we are going to install a very cool tool known as no demon that allows a node.js application restarts automatically every time there is a change. Write the following command with “-g” that will allow installing the package as global so that it can be used from anywhere. The problem associated with the local installation of nodemon is that no demon will not be available in your system path and the local installation of nodemon can be run by calling it from within an npm script.</p>
<pre><code class="lang-bash">$ npm install -g nodemon
</code></pre>
<p>Nodemon can also be installed as a development dependency with the following command in the terminal.</p>
<pre><code class="lang-bash">$ npm install — save-dev nodemon
</code></pre>
<h2 id="heading-create-a-basic-server"><strong>Create a Basic Server</strong></h2>
<p>Let’s start coding! First, we are going to create a file and name it as “server.js” in the project root directory. Run the following command in the terminal or create it from visual studio code.</p>
<pre><code class="lang-bash">$ sudo touch server.js
</code></pre>
<p>Now, we will start writing our code in “server.js”. First, we are going to import the “express” module. For the importing module, we are going to use the “require” function.</p>
<pre><code class="lang-bash">require(“express”)
</code></pre>
<p>The imported module is required to be in a variable. Variable can be declared as var, let or const. You can find details about variable declaration here :</p>
<pre><code class="lang-bash">https://dev.to/sarah_chima/var-let-and-const--whats-the-difference-69e
</code></pre>
<p>Variables declared with the const maintain constant values but variables with var can be updated. We are going to import “express” to a const variable. Then an instance of the imported module will be created through the “app” variable. the “app” is an instance of express. you can set the environment variable “PORT” to tell your web server what port to listen on. So process.env.PORT || 3000 means: whatever is in the environment variable PORT, or 3000 if there’s nothing there. So you pass that app.listen, or to app.set(‘port’, …), and that makes your server able to accept a parameter from the environment what port to listen on. If you pass 3000 hard-coded to app.listen(), you’re always listening on port 3000, which might be just for you, or not, depending on your requirements and the requirements of the environment in which you’re running your server.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(‘express’); <span class="hljs-comment">// importing Express</span>
<span class="hljs-keyword">const</span> app = express(); <span class="hljs-comment">// instance of express</span>
<span class="hljs-keyword">const</span> port = process.env.PORT || <span class="hljs-number">3000</span>; <span class="hljs-comment">// Defining port by environmental parameter or 3000// Create a routing </span>
app.get(‘/’,<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">req,res</span>)</span>{
 res.send(‘Server is running.’)
})<span class="hljs-comment">// App is listening to user-defined port or 300 and printing the information to the console.</span>
app.listen(port, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">req,res</span>)</span>{
 <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Server is listening on port <span class="hljs-subst">${port}</span>!`</span>)
})
</code></pre>
<p>Run the server using the command :</p>
<pre><code class="lang-bash">$ node server.js
</code></pre>
<p>Now, go to the following URL to access the server.</p>
<pre><code class="lang-bash">http://localhost:3000
</code></pre>
<p>By going to this URL, we are sending a GET request through our web client. This is the concept of routing. We are going to discuss this later in this section. Now if we are going to make changes, we have to stop the server by pressing ctrl + c and then start the server again by using the above command. To avoid running the server again and again by running the same command, we are going to use the nodemon.</p>
<p>Go to the package.json and replace test in the script with the following:</p>
<pre><code class="lang-yaml"><span class="hljs-attr">"scripts":</span> {
<span class="hljs-attr">"devStart":</span> <span class="hljs-string">"nodemon server.js"</span>
}
</code></pre>
<p>Then you can start the server using nodemon by using the following command.</p>
<pre><code class="lang-bash">$ npm start devStart
</code></pre>
<p>Alternatively, you can directly start your server by running following command:</p>
<pre><code class="lang-bash">$ nodemon server.js
</code></pre>
<p>Now, whenever you make a code change, the server will automatically restart. Currently, our server is running in port 3000. We can also define our port through set or exporting the port parameter through env. If you want to run it just once, run the following command.</p>
<pre><code class="lang-bash">$ PORT=1234 node server.js
</code></pre>
<p>You don't have to restart the server as nodemon will do it automatically. To set the PORT More permanently, use the following command.</p>
<pre><code class="lang-bash">$ <span class="hljs-built_in">export</span> PORT=3000
$ node server.js
</code></pre>
<p>For Windows, use the following command.</p>
<pre><code class="lang-bash">$ <span class="hljs-built_in">set</span> PORT=3000
</code></pre>
<p>For Windows PowerShell:</p>
<pre><code class="lang-bash">$ env:PORT = 3000
</code></pre>
<p>Another method to set the env parameter is though dotenv package.</p>
<pre><code class="lang-bash">npm install dotenv
</code></pre>
<p>Add this line to the start of the server.</p>
<pre><code class="lang-bash">require(‘dotenv’).config()
</code></pre>
<p>Create a .env file in the root directory of your project. Add</p>
<pre><code class="lang-bash">PORT = 3000
</code></pre>
<p>create .gitignore because you don’t want to import .env to git.</p>
<p>So, our basic server is running. But currently, there is not routing that is configured. We are going to discuss the routing and configure some endpoints.</p>
<h2 id="heading-routing"><strong>Routing</strong></h2>
<p>Routing refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on). Each route can have one or more handler functions, which are executed when the route is matched. Route definition takes the following structure:</p>
<p>Route definition takes the following structure:</p>
<pre><code class="lang-javascript">app.METHOD(PATH, HANDLER)
</code></pre>
<p>METHOD is an HTTP request method, in lowercase. PATH is a path on the server. HANDLER is the function executed when the route is matched. Write down the following code to create routing using GET, POST, PUT and DELETE methods.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">require</span>(<span class="hljs-string">'dotenv'</span>).config()
<span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>); 
<span class="hljs-keyword">const</span> app = express(); <span class="hljs-comment">// instance of express</span>
<span class="hljs-keyword">const</span> port = process.env.PORT || <span class="hljs-number">3000</span>; <span class="hljs-comment">// GET requestapp.get('/', function (req, res) {</span>
res.status(<span class="hljs-number">200</span>).send(<span class="hljs-string">'Server is up and running.'</span>)
})<span class="hljs-comment">// POST requestapp.post('/', function (req, res) {</span>
res.status(<span class="hljs-number">200</span>).send(<span class="hljs-string">'This is a POST request'</span>)
})<span class="hljs-comment">// PUT Requestapp.put('/', function (req, res) {</span>
res.status(<span class="hljs-number">200</span>).send(<span class="hljs-string">'This is a PUT request'</span>)
})<span class="hljs-comment">// PATCH Requestapp.patch('/', function (req, res) {</span>
res.status(<span class="hljs-number">200</span>).send(<span class="hljs-string">'This is a PATCH request'</span>)
})<span class="hljs-comment">// DELETE Requestapp.delete('/', function (req, res) {</span>
res.status(<span class="hljs-number">200</span>).send(<span class="hljs-string">'This is a DELETE request'</span>)
})<span class="hljs-comment">// App is listening to user-defined port or 300 and printing the information to the console.app.listen(port, function (req, res) {</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Server is listening on port <span class="hljs-subst">${port}</span>!`</span>)
})
</code></pre>
<p>To test your routing, you need to have POSTMAN or any other API endpoint testing tool. But for simplicity, I am going to use REST Client, an extension in visual studio code to test endpoints. You can install it in your VS editor by Quick doing open (<code>Ctrl+P</code>) and paste the following command:</p>
<pre><code class="lang-bash">ext install humao.rest-client
</code></pre>
<p>Let's create a new file with extension rest. I am creating a <a target="_blank" href="http://test.rest">test.rest</a> to test endpoints. Now write down the following to start testing.</p>
<pre><code class="lang-bash"><span class="hljs-comment">### GET Request</span>
GET http://localhost:3000<span class="hljs-comment">### POST Request</span>
POST http://localhost:3000<span class="hljs-comment">### DELETE Request</span>
DELETE http://localhost:3000<span class="hljs-comment">### PUT Request</span>
PUT http://localhost:3000<span class="hljs-comment">### PATCH Request</span>
PATCH http://localhost:3000
</code></pre>
<p>There should be a 'Send Request' just above the request. You need to press it to test your endpoints.</p>
<p><img src="https://miro.medium.com/max/700/1*cJi0UxUHXf8S3QoENFEMHQ.png" alt /></p>
<p>If the request is successful, you should see output similar to following:</p>
<pre><code class="lang-bash">HTTP/1.1 200 OK 
X-Powered-By: Express 
Content-Type: text/html; 
charset=utf-8 
Content-Length: 25 
ETag: W/<span class="hljs-string">"19-mtGkfbkTqxz/NZr8uVnRPTJZzm8"</span> 
Date: Fri, 03 Apr 2020 21:18:53 GMT 
Connection: close  Server is up and running.
</code></pre>
<p>In case endpoints are not working, it should return a 404 error similar like the following:</p>
<pre><code class="lang-bash">HTTP/1.1 404 
Not Found X-Powered-By: Express 
Content-Security-Policy: default-src <span class="hljs-string">'none'</span> 
X-Content-Type-Options: nosniff Content-Type: text/html; charset=utf-8 Content-Length: 140 
Date: Fri, 03 Apr 2020 21:20:29 GMT 
Connection: close  
&lt;!DOCTYPE html&gt; 
&lt;html lang=<span class="hljs-string">"en"</span>&gt; 
&lt;head&gt; &lt;meta charset=<span class="hljs-string">"utf-8"</span>&gt; 
&lt;title&gt;Error&lt;/title&gt;
 &lt;/head&gt; 
&lt;body&gt; &lt;pre&gt;Cannot GET /r&lt;/pre&gt; &lt;/body&gt; 
&lt;/html&gt;
</code></pre>
<h2 id="heading-folder-structure"><strong>Folder Structure</strong></h2>
<p>The code we have just written is working just fine but to make it standard, we should not put all our code into a single script, with the time being, it will a large file with lots of coding and you will find it difficult to write more features. To solve this problem, we are going to split our code into several scripts. In our server.js, we are going to keep server handling code and we are going to create a different script that will contain all the routes. This script can be exported as a module and be called in server.js and all the endpoints should work like just before. Let’s create a new directory named ‘routes’ and create a file named ‘routes.js’.</p>
<pre><code class="lang-bash">mkdir routes
touch routes/routes.js
</code></pre>
<p>Let’s start writing code in routes.js. First, we will import express like before and then create an instance of express, but not in ‘app’ variable with ‘express()’, instead we are going to use as following:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(‘express’);
<span class="hljs-keyword">const</span> router = express.Router();
</code></pre>
<p>Let’s take out the routing code from the server and place them in routes.js. We are going to replace our app.METHOD with router.METHOD. At the end, we need to export it as a module.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// GET requestrouter.get(‘/’, function (req, res) {</span>
res.status(<span class="hljs-number">200</span>).send(‘Server is up and running.’)
})<span class="hljs-comment">// POST requestrouter.post(‘/’, function (req, res) {</span>
res.status(<span class="hljs-number">200</span>).send(‘This is a POST request’)
})<span class="hljs-comment">// PUT Requestrouter.put(‘/’, function (req, res) {</span>
res.status(<span class="hljs-number">200</span>).send(‘This is a PUT request’)
})<span class="hljs-comment">// PATCH Requestrouter.patch(‘/’, function (req, res) {</span>
res.status(<span class="hljs-number">200</span>).send(‘This is a PATCH request’)
})<span class="hljs-comment">// DELETE Requestrouter.delete(‘/’, function (req, res) {</span>
res.status(<span class="hljs-number">200</span>).send(‘This is a DELETE request’)
})<span class="hljs-built_in">module</span>.exports = router;
</code></pre>
<p>Now, we can use routes.js as modules and can call this module from our server.js. To do so, let’s add these following two lines to server.js:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> router = <span class="hljs-built_in">require</span>(‘./routes/routes’)
app.use(‘/’,router)
</code></pre>
<p>There will be no routes in the server now. The final code of server.js will be as follows:</p>
<pre><code class="lang-bash">require(‘dotenv’).config()const express = require(‘express’); // importing Express
const app = express(); // instance of express
const port = process.env.PORT || 3000; // Defining port by environmental parameter or 3000const router = require(‘./routes/routes’)
app.use(‘/’,router)// App is listening to user-defined port or 300 and printing the information to the console.app.listen(port, <span class="hljs-keyword">function</span> (req, res) {
console.log(`Server is listening on port <span class="hljs-variable">${port}</span>!`)
})
</code></pre>
<p>Test the endpoints with the test.rest. It should return 200 http codes and all endpoints should just work fine.</p>
<h2 id="heading-push-your-code-to-github"><strong>Push your code to GitHub</strong></h2>
<p>Now you are done with coding and testing. Let’s push your code to your GitHub. I assume you have already installed git, else you can do so b following the command:</p>
<pre><code class="lang-bash">$ sudo apt install git$ git config — global user.name “username”$ git config — global user.email “email”
</code></pre>
<p>Run the following command to push your code to GitHub (It may ask for your git username and password) :</p>
<pre><code class="lang-bash">$ git add .$ git ommit -m “Your commit message”$ git push
</code></pre>
<p>Congratulations on your first rest api development! I enjoyed a lot writing these first two parts and I hope you have also enjoyed reading and creating your first API. In the next part, I am going to cover some more important topics. Ask me any questions if you face any kind of difficulties during following this article.</p>
]]></content:encoded></item><item><title><![CDATA[RESTful API development with Node.js and Express: Setup and configure the development environment ( Part — 1)]]></title><description><![CDATA[Probably you have heard about it a lot and you still don’t have a clear idea of what is RESTful API, what it does and how to create one! Don’t worry. I was in the same situation for a longer time than you think and it took quite some time to learn it...]]></description><link>https://cloudopscamp.com/restful-api-development-with-nodejs-and-express-setup-and-configure-the-development-environment-part-1</link><guid isPermaLink="true">https://cloudopscamp.com/restful-api-development-with-nodejs-and-express-setup-and-configure-the-development-environment-part-1</guid><category><![CDATA[REST API]]></category><category><![CDATA[AWS]]></category><category><![CDATA[Docker]]></category><dc:creator><![CDATA[Humayun Rashid]]></dc:creator><pubDate>Fri, 03 Feb 2023 20:30:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1677263890920/964c6fd2-545e-4ce7-aaca-3c96c67a40eb.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Probably you have heard about it a lot and you still don’t have a clear idea of what is RESTful API, what it does and how to create one! Don’t worry. I was in the same situation for a longer time than you think and it took quite some time to learn it!<br />The best way to learn about RESTful API is to learn by doing. Trust me! You will learn a lot if you just start creating one and I can promise you that no other stack except NodeJs and Express will help you to get started!</p>
<p>But wait a minute! You don’t know anything about NodeJS, along with Express and even JS. Now what?</p>
<p>Just don’t worry and sit tight. This is going to be several parts articles that will help you to get to know about RESTful API design and by the end of this series, you may not be a professional developer but still, you will learn a lot of good stuff.</p>
<p>Let’s get started with a little bit of description of RESTful API! Here it goes!</p>
<h1 id="heading-what-is-restful-api"><strong>What is RESTful API</strong></h1>
<p>RESTful API is a client-server-based architecture that utilizes stateless operations to access and manipulate data through HTTP requests. REST stands for REpresentational State Transfer. One of the principal requirements of a Restful architecture is that it consists of two core elements, client and server. Clients request resources from the server to do different operations. RESTful API-based system is stateless as each request from the client to the server must contain all of the information that is essential to understand the request, and cannot take advantage of any stored context on the server. REST API is designed to create an endpoint for specific operations using HTTP protocol and CRUD functionality (CRUD stands for Create, Read, Update, Delete). HTTP defines a set of request methods to indicate the desired action to be performed for a given resource based on CRUD functionality. The HTTP protocols that are used for designing REST API are listed below.</p>
<ul>
<li><p>POST — create a resource or generally provide data</p>
</li>
<li><p>GET — retrieve an index of resources or an individual resource</p>
</li>
<li><p>PUT — create or replace a resource</p>
</li>
<li><p>PATCH — update/modify a resource</p>
</li>
<li><p>DELETE — remove a resource</p>
</li>
</ul>
<p>Enough of talking! Let’s get started with hands-on.</p>
<h1 id="heading-restful-api-development-by-nodejs-and-express-setup-and-configure-the-development-environment"><strong>RESTful API development by Node.js and Express: Setup and configure the development environment</strong></h1>
<p>To get started with reSTful API development, first, we need to create a development environment. The following things are needed to be installed and configured before the jump to coding. We will only use stacks that are open-source and free to use.</p>
<ul>
<li><p>Programming Stack and package manager -NodeJS &amp; NPM</p>
</li>
<li><p>Source code editor — Visual Studio Code / WebStorm (Editor)</p>
</li>
<li><p>REST API Testing Tools — POSTMAN / Insomnia</p>
</li>
<li><p>Version Control — GitHub</p>
</li>
</ul>
<h2 id="heading-nodejs-and-npm"><strong>Node.js and NPM</strong></h2>
<p>NodeJS is Chrome’s V8 JavaScript engine-based runtime that is open-source, lightweight, efficient server and vastly used for developing a client-server-based application. The performance of NodeJs is non-blocking and asynchronous and it is an event-driven based runtime environment. The official package manager for Node is NPM.</p>
<h2 id="heading-windows-as-well-as-mac"><strong>Windows ( as well as MAC )</strong></h2>
<p>Download the required installer from the following link, install Node by double-clicking on the downloaded file and following the installation prompts.</p>
<pre><code class="lang-plaintext">https://nodejs.org/en/
</code></pre>
<h2 id="heading-install-node-via-homebrew-mac-and-linux"><strong>Install Node via Homebrew ( MAC and Linux)</strong></h2>
<p>Homebrew simplifies the installation of software on the Mac OS X operating system. Install Homebrew for MAC or Linux using the following command :</p>
<pre><code class="lang-bash">/bin/bash -c <span class="hljs-string">"<span class="hljs-subst">$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)</span>"</span>
</code></pre>
<p>or you can also use the following command:</p>
<pre><code class="lang-bash">/usr/bin/ruby -e “$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)<span class="hljs-string">"
brew doctor</span>
</code></pre>
<p>In the terminal type the following command to install Node.</p>
<pre><code class="lang-bash">brew install node
</code></pre>
<p>If everything installed successfully then you can type in the following command in the terminal to check the Node and NPM version.</p>
<pre><code class="lang-bash">node -v
npm -v
</code></pre>
<h2 id="heading-ubuntu-1804-install-from-ubuntu-binary-distributions-repository"><strong>Ubuntu 18.04 (Install from Ubuntu binary distributions repository )</strong></h2>
<p>The easiest way to install the most recent LTS version of Node 10.x is to use the package manager to get it from the Ubuntu binary distributions repository. This can be done very simply by running the following two commands on the terminal:</p>
<pre><code class="lang-plaintext">curl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash — 
sudo apt-get install -y nodejs
</code></pre>
<h2 id="heading-install-source-code-editor-visual-studio-code"><strong>Install Source code editor ( Visual Studio Code)</strong></h2>
<p>Visual Studio Code is a source code editor developed by Microsoft for Windows, Linux, and <a target="_blank" href="http://macOS.It">macOS.It</a> is a simple yet powerful and fast source code editor with support for hundreds of languages with features like syntax highlighting, bracket-matching, auto-indentation, box-selection, snippets, intuitive keyboard shortcuts, easy customization, and community-contributed keyboard shortcut mappings and many more. You can get started with visual studio code by downloading from the following links. It is important that turn on the autosave mode.</p>
<p><strong>Linux:</strong></p>
<pre><code class="lang-plaintext">https://code.visualstudio.com/docs/setup/linux
</code></pre>
<p><strong>macOS:</strong></p>
<pre><code class="lang-plaintext">https://code.visualstudio.com/docs/setup/mac
</code></pre>
<p><strong>Windows:</strong></p>
<pre><code class="lang-plaintext">https://code.visualstudio.com/docs/setup/windows
</code></pre>
<p>You need to install a plugin that will make your coding experience more fun. The plugin’s name is Prettier, that’s a tool that automatically covert messy code into a readable format. Install it from here:</p>
<pre><code class="lang-plaintext">https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode
</code></pre>
<h2 id="heading-restful-api-testing-tools-postman-andamp-insomnia"><strong>RESTful API testing tools (Postman &amp; Insomnia)</strong></h2>
<p>Postman is a collaboration platform for API development. We will use to test our endpoints that will be created during creating RESTful API. POSTMAN can be downloaded and install for Windows and MAC from here:</p>
<pre><code class="lang-plaintext">https://www.postman.com/downloads/
</code></pre>
<p>Postman is also available from google chrome store that can be used as Chrome extension :</p>
<pre><code class="lang-plaintext">https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=fi
</code></pre>
<p>Another famous tool for API testing is Insomnia. It is a free cross-platform desktop for interacting with HTTP-based APIs. Download insomnia from here:</p>
<pre><code class="lang-plaintext">https://support.insomnia.rest/article/11-getting-started
</code></pre>
<h2 id="heading-setup-github"><strong>Setup GitHub</strong></h2>
<p>GitHub is an open-source repository hosting service with features of tracking changes in a changelog so that you can know exactly what has been changed in your code each time.</p>
<h2 id="heading-linux"><strong>Linux</strong></h2>
<p>Open a terminal window. Copy &amp; paste the following into the terminal window and hit Return. You may be prompted to enter your password.</p>
<pre><code class="lang-bash">sudo apt update
sudo apt upgrade
sudo apt install git
</code></pre>
<h2 id="heading-mac"><strong>Mac</strong></h2>
<p>Copy &amp; paste the following into the terminal window and hit Return.</p>
<pre><code class="lang-bash">brew install git
</code></pre>
<p>You can use Git now.</p>
<h2 id="heading-windows"><strong>Windows</strong></h2>
<p>Git for windows can be downloaded from here:</p>
<pre><code class="lang-bash">https://gitforwindows.org/
</code></pre>
<p>If you are new to Git, I will suggest you read:</p>
<pre><code class="lang-bash">https://kbroman.org/github_tutorial/pages/first_time.html
</code></pre>
<p>You will eventually get a bit more understanding about configuring GitHub for the first time.</p>
<p>Enough of talking about setting up the environment. It is now time to start development. The second part of this article will guide you on how you can start coding to make your first API using node js and express. You can read it <a target="_blank" href="https://medium.com/@humayun.ashid/restful-api-development-with-node-js-and-express-getting-started-with-coding-part-2-7c79e27fafbb?sk=4b1d9cd0be60190d65c80cd37c6ca507">here</a>.</p>
<p>Happy Coding!</p>
]]></content:encoded></item></channel></rss>