<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Vaishnavi Rawool</title>
    <description>The latest articles on DEV Community by Vaishnavi Rawool (@vaishnavi_rawool).</description>
    <link>https://dev.to/vaishnavi_rawool</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1641165%2Fafc5e6a2-70f7-4feb-8ec0-cc7404a944ec.jpeg</url>
      <title>DEV Community: Vaishnavi Rawool</title>
      <link>https://dev.to/vaishnavi_rawool</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/vaishnavi_rawool"/>
    <language>en</language>
    <item>
      <title>Introduction to Sequelize: Simplifying Database Operations in Node.js</title>
      <dc:creator>Vaishnavi Rawool</dc:creator>
      <pubDate>Thu, 27 Jun 2024 07:38:36 +0000</pubDate>
      <link>https://dev.to/vaishnavi_rawool/introduction-to-sequelize-simplifying-database-operations-in-nodejs-322a</link>
      <guid>https://dev.to/vaishnavi_rawool/introduction-to-sequelize-simplifying-database-operations-in-nodejs-322a</guid>
      <description>&lt;h2&gt;
  
  
  What is a ORM ?
&lt;/h2&gt;

&lt;p&gt;ORM (Object-Relational Mapping) bridges databases and object-oriented programming by mapping database tables to objects in code. It allows developers to interact with databases using familiar programming constructs, abstracting away SQL queries for easier development and maintenance of applications.&lt;/p&gt;

&lt;h2&gt;
  
  
  Advantages of ORMs
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;ORMs abstract away the need to write raw SQL queries directly in your application code, reducing the complexity&lt;/li&gt;
&lt;li&gt;Complex database operations, such as JOINs and GROUP BYs, can be expressed in a simpler syntax using ORM methods and APIs.&lt;/li&gt;
&lt;li&gt;Supports transactions and rollback mechanisms&lt;/li&gt;
&lt;li&gt;ORMs can significantly reduce development time and effort&lt;/li&gt;
&lt;li&gt;ORMs includes features for optimizing query performance (e.g., lazy loading).&lt;/li&gt;
&lt;li&gt;Same application logic can be used with different database systems (e.g., MySQL, PostgreSQL, SQLite) without significant changes&lt;/li&gt;
&lt;li&gt;ORMs offer built-in validation mechanisms (e.g., unique, not null). You can also write custom validations (e.g., email regex validation, phone number validation)&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Disadvantages of ORMs
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;ORMs introduce a learning curve as developers need to familiarize themselves with the ORM's API and its querying methods&lt;/li&gt;
&lt;li&gt;Understanding how the ORM translates application code into SQL queries often requires digging into ORM logs or debugging mechanisms.&lt;/li&gt;
&lt;li&gt;Despite the ORM's capabilities, there are situations where developers may need to resort to writing raw SQL queries for certain operations. Sequelize, for example, provides mechanisms for executing raw SQL queries when needed.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Getting started with Sequelize
&lt;/h2&gt;

&lt;h2&gt;
  
  
  1] Installation
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install sequelize

or

yarn add sequelize
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  2]You'll also have to manually install the driver for your database of choice:
&lt;/h2&gt;

&lt;p&gt;One of the following:&lt;/p&gt;

&lt;p&gt;$ npm install --save pg pg-hstore # Postgres&lt;/p&gt;

&lt;p&gt;$ npm install --save mysql2&lt;/p&gt;

&lt;p&gt;$ npm install --save mariadb&lt;/p&gt;

&lt;p&gt;$ npm install --save sqlite3&lt;/p&gt;

&lt;p&gt;$ npm install --save tedious # Microsoft SQL Server&lt;/p&gt;

&lt;p&gt;$ npm install --save oracledb # Oracle Database&lt;/p&gt;

&lt;h2&gt;
  
  
  Connecting to a Database
&lt;/h2&gt;

&lt;p&gt;1] Create a config.json and store development db details as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{

    "development": {

      "username": "postgres",

      "password": "root",

      "database": "travel",

      "host": "localhost",

      "dialect": "postgres",

      "port":"5432"

    }

  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Similarly you can add details of other environments e.g., staging/production&lt;/p&gt;

&lt;p&gt;2] Create a dbConfig.js file and paste the following  code :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const path = require('path');

const { Sequelize } = require('sequelize');

// Load Sequelize configurations from config.json file
const env = process.env.NODE_ENV || 'development'; // default environment is development if not set explicitly

const config = require("./config.json")[env];

// You will have to pass database name, username, password, host, port and dialect (in this case postgres) inorder to create a instance.

const sequelize = new Sequelize(config.database, config.username, config.password, {

  host: config.host,

  dialect: "postgres",

  port: config.port

});

// export the newly created instance from this file
  module.exports.sequelize = sequelize;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Sequelize provides &lt;strong&gt;authenticate()&lt;/strong&gt; function to check whether the database connection was successful&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;try {

  await sequelize.authenticate();

  console.log('Connection has been established successfully.');

} catch (error) {

  console.error('Unable to connect to the database:', error);

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Let us explore the basics of model creation in sequelize.
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;In Sequelize, a model represents a table in a database.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;You define a table structure i.e columns, relationships (one-to-one, one-to-many etc), indexes, hooks etc using a model&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Columns in a Sequelize model are defined using attributes.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Attributes can specify various parameters, including:&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;ol&gt;
&lt;li&gt;type: Specifies the data type of the column (e.g., STRING, INTEGER, DATE).&lt;/li&gt;
&lt;li&gt;allowNull: Indicates whether the column can be null (true or false).&lt;/li&gt;
&lt;li&gt;defaultValue: Sets a default value for the column if not provided.&lt;/li&gt;
&lt;li&gt;primaryKey: Marks the column as the primary key (true or false).&lt;/li&gt;
&lt;li&gt;unique: Ensures the column values are unique (true or false).&lt;/li&gt;
&lt;li&gt;Other constraints like autoIncrement, references, onDelete, etc., can also be defined depending on the database relationship requirements.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Create a user.model.js file inside models folder that has a simple User model configuration code.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const { Sequelize, DataTypes, Model } = require('sequelize');

const sequelize = require(‘./dbConfig.js’);

class User extends Model {}

User.init(
  {

// id attribute which is a primary key

   id: {
     type: DataTypes.INTEGER,
     primaryKey: true,
     autoIncrement: true
    },

    firstName: {
      type: DataTypes.STRING,
      allowNull: false,
    },

    lastName: {
      type: DataTypes.STRING,
      // allowNull defaults to true
    },
  },
  {
    // Other model options go here
    sequelize, // We need to pass the connection instance that we have created earlier
    modelName: 'User', // We need to choose the model name
  },
);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can define relationships between tables using sequelize. Consider the example below, where we create a one-to-many association between the User and Address tables using hasMany:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;User.Addresses = User.hasMany(Address);&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Similarly, you can create one-to-one and many-to-many relations as well. Read in detail about relationships &lt;br&gt;
&lt;a href="https://sequelize.org/docs/v6/advanced-association-concepts/creating-with-associations/"&gt;Model Associations&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Model Synchronization
&lt;/h2&gt;

&lt;p&gt;When you define a model, you're telling Sequelize a few things about its table in the database. However, what if the table actually doesn't even exist in the database? What if it exists, but it has different columns, less columns, or any other difference?&lt;/p&gt;

&lt;p&gt;This is where model synchronization comes in. A model can be synchronized with the database by calling model.sync(options), an asynchronous function (that returns a Promise). With this call, Sequelize will automatically perform an SQL query to the database. Note that this changes only the table in the database, not the model in the JavaScript side.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;User.sync() - This creates the table if it doesn't exist (and does nothing if it already exists)&lt;/li&gt;
&lt;li&gt;User.sync({ force: true }) - This creates the table, dropping it first if it already existed&lt;/li&gt;
&lt;li&gt;User.sync({ alter: true }) - This checks what is the current state of the table in the database (which columns it has, what are their data types, etc), and then performs the necessary changes in the table to make it match the model.&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;
  
  
  Let us explore some basics CRUD operations with the help of sequelize:
&lt;/h2&gt;

&lt;p&gt;1] Create a new record&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;create() method is asynchronous hence we have to put await before it&lt;br&gt;
Import User from user.model.js file&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const User = require(‘../model/user.model.js’);

const jane = await User.create({ firstName: 'Jane', lastName: 'Doe' });


// Jane exists in the database now!
console.log(jane instanceof User); // true
console.log(jane.name); // "Jane"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;2]  Simple SELECT queries (all of the querying methods are asychronous)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// fetch all users from user table

const users = await User.findAll();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// fetch certain fields from user table

await User.findAll({  attributes: [firstName,’lastName’]});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//apply where clause and fetch user with id = 1

await User.findAll({ where: {  id: 1, }});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Read more about model querying here: &lt;a href="https://sequelize.org/docs/v6/core-concepts/model-querying-basics/"&gt;Model Querying&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  3] Update query
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;await User.update( { lastName: 'Doe' },{
    where: {
      lastName: null,
    },
  },
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  4] Delete query
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Delete everyone named "Jane"
await User.destroy({
  where: {
    firstName: 'Jane',
  },
});

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  CONCLUSION
&lt;/h2&gt;

&lt;p&gt;Sequelize offers a comprehensive documentation covering various SQL methods along with advanced topics such as Joins, Aggregate functions, Transactions, and Lazy Loading. Its user-friendly navigation makes it accessible even for beginners, helping in a thorough understanding of the ORM. I highly recommend exploring Sequelize's documentation to delve deeper into its capabilities. &lt;a href="https://sequelize.org/docs/v6/category/core-concepts/"&gt;Sequelize&lt;/a&gt; &lt;/p&gt;

</description>
      <category>node</category>
      <category>database</category>
      <category>sql</category>
      <category>javascript</category>
    </item>
    <item>
      <title>Creating a Simple RESTful API with Node.js</title>
      <dc:creator>Vaishnavi Rawool</dc:creator>
      <pubDate>Wed, 19 Jun 2024 17:54:05 +0000</pubDate>
      <link>https://dev.to/vaishnavi_rawool/creating-a-simple-restful-api-with-nodejs-a96</link>
      <guid>https://dev.to/vaishnavi_rawool/creating-a-simple-restful-api-with-nodejs-a96</guid>
      <description>&lt;h2&gt;
  
  
  What is an API ?
&lt;/h2&gt;

&lt;p&gt;An API, or application programming interface, is a set of rules or protocols that enables software applications to communicate with each other to exchange data, features and functionality.It’s useful to think about API communication in terms of a request and response between a client and server. The application submitting the request is the client, and the server provides the response. The API is the bridge establishing the connection between them.&lt;/p&gt;

&lt;h2&gt;
  
  
  What are the types of APIs?
&lt;/h2&gt;

&lt;p&gt;Some of the most common type of APIs are:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;RESTful APIs&lt;/strong&gt;: Use standard HTTP methods like GET, POST, PUT, DELETE to interact with resources identified by URLs. They are stateless and follow the principles of REST for scalability and simplicity in client-server communication.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;SOAP APIs&lt;/strong&gt;: Employ XML-based messaging and typically use protocols like HTTP or SMTP. They adhere to a strict messaging format and rely on a contract (WSDL) for defining endpoints and operations, making them suitable for complex integrations requiring strong reliability and security measures.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  What is REST ?
&lt;/h2&gt;

&lt;p&gt;REST stands for Representational State Transfer. It's an architectural style for designing networked applications. Here’s a simple explanation:&lt;/p&gt;

&lt;p&gt;Imagine you're in a restaurant. When you want to order food, you ask the waiter for the menu, choose your dishes, and tell the waiter your order. REST works similarly in the digital world:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Resources: Think of these as items on the menu — they can be data or functionality (like getting information or saving data).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;HTTP Methods: These are like actions you can take with your order, such as GET (to retrieve data), POST (to add new data), PUT (to update data), DELETE (to remove data).&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;URLs: Just like how you tell the waiter where to bring your food, URLs specify where to find or interact with resources.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;RESTful APIs use these concepts to allow different systems to communicate over the internet, making it easier for computers to share and use information effectively.&lt;/p&gt;

&lt;p&gt;Know everything about REST -&amp;gt; &lt;a href="https://restfulapi.net/"&gt;https://restfulapi.net/&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  How to create REST APIs in Node.js ?
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;- Tools Required&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Node.js (Node.js is a runtime environment that allows developers to run JavaScript code outside of a web browser, enabling server-side scripting and building scalable network applications)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Express.js (Express.js is a minimalist Node.js web framework with features for routing, middleware support, and simplified handling of HTTP requests and responses.)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;VS Code (Code Editor) or any other editor of your choice&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Step 1:&lt;/strong&gt; Install latest versions of above mentioned software&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 2:&lt;/strong&gt; Creating a Node Project&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Create a new folder called &lt;strong&gt;node-rest-apis&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt; When installing Node.js, &lt;strong&gt;npm&lt;/strong&gt;, the package manager, is also installed, that helps us create a new node project&lt;/li&gt;
&lt;li&gt;Open the integrated terminal within VS Code with the following command -&amp;gt; &lt;strong&gt;Ctrl + `&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;Enter the following command -&amp;gt; &lt;strong&gt;npm init&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;Follow the prompt -&amp;gt; npm init will ask you for information such as the project name, version, description, entry point (usually index.js), test command, repository URL, author information, and license. You can either fill out these details or simply press Enter to accept the default values.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Step 3:&lt;/strong&gt; Install express with the help of npm: &lt;strong&gt;npm install express&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fn6sf0c6oycp5emgokgne.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fn6sf0c6oycp5emgokgne.png" width="800" height="120"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 4:&lt;/strong&gt; Create a file named &lt;strong&gt;index.js&lt;/strong&gt; file (you may give it any name of your choice)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 5:&lt;/strong&gt; Overview of the files/folders created&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;package.json: package.json file stores metadata about your project and its dependencies. Whenever we install new dependencies, they are automatically added to the dependencies section of the package.json file in our Node.js project&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;node_modules: This directory houses all the dependencies that your project requires. These dependencies are installed via npm or yarn and are listed in package.json.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;index.js : This file usually serves as the entry point to your application. It initializes your application, sets up configurations, and may start the server if it's a web application.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Step 6:&lt;/strong&gt; Install nodemon &lt;strong&gt;npm install nodemon&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxq4pg7u5r40r91abdmvo.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxq4pg7u5r40r91abdmvo.png" alt="Image description" width="800" height="254"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Nodemon is a utility tool for Node.js that helps in development by automatically restarting the Node application when changes are detected in the codebase. This eliminates the need to manually stop and restart the server after every code change, thus speeding up the development workflow.&lt;/p&gt;

&lt;p&gt;Make changes to the start script and run the server using the following command : &lt;strong&gt;npm start&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F057fyluh9jwjddtyowyf.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F057fyluh9jwjddtyowyf.png" alt="Image description" width="800" height="574"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 7:&lt;/strong&gt; Let’s start by creating a node server&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fdtvizld3hrevuwmosg9e.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fdtvizld3hrevuwmosg9e.png" alt="Image description" width="800" height="392"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Code explanation:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;require('express'): Imports the Express module.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;const app = express(): Creates an instance of the Express application.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;const port = 3000: Specifies the port number where the server will listen for incoming requests.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;app.listen(port, ...): Starts the Express server on the specified port (3000 in this case) and logs a message to the console once the server is running.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For running your application add the following start script in package.json:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fopz1tk887tkcbftolzxb.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fopz1tk887tkcbftolzxb.png" alt="Image description" width="800" height="420"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You can you run your application with the following command: &lt;strong&gt;node index.js&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fg53tjagzdo8uc0kwbjo3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fg53tjagzdo8uc0kwbjo3.png" width="800" height="160"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 8:&lt;/strong&gt; Create a basic API route in express&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5hujjb4w66b3q09sorf3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5hujjb4w66b3q09sorf3.png" width="800" height="504"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Defines a route handler for the GET request at &lt;strong&gt;/test&lt;/strong&gt;. When a GET request is made to /test, it sends back a JSON response { message: 'This is a sample API route' }&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 9:&lt;/strong&gt; Testing the API using Postman&lt;/p&gt;

&lt;p&gt;Postman is a collaborative platform for API development that simplifies the process of designing, testing, and debugging APIs.&lt;/p&gt;

&lt;p&gt;The API gives a successful response&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6g9elsleoxuomo7iwl1q.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6g9elsleoxuomo7iwl1q.png" alt="Image description" width="800" height="493"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 10&lt;/strong&gt;: Let’s organize the code in a MVC (Model, View, Controller) like pattern&lt;/p&gt;

&lt;p&gt;Create controllers, services, routes, models folder in the root directory&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 11:&lt;/strong&gt; Create a file name &lt;strong&gt;user.model.js&lt;/strong&gt; under models folder&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frb3r7xbhj5w37cmdt238.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frb3r7xbhj5w37cmdt238.png" alt="Image description" width="800" height="440"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;These functions mimic basic CRUD (Create, Read, Update, Delete) operations commonly performed on user data in applications. Other CRUD operations like create, update, and delete could be added as needed to complete the CRUD functionality.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fyiy5mju3usukp2oriewl.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fyiy5mju3usukp2oriewl.png" alt="Image description" width="800" height="261"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 12:&lt;/strong&gt;  Create a file name &lt;strong&gt;user.service.js&lt;/strong&gt; under services folder&lt;/p&gt;

&lt;p&gt;The service files have all the business logic implemented. For eg: all the users related CRUD operations will go inside this file&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F7cflww9ymardpa6l0li1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F7cflww9ymardpa6l0li1.png" alt="Image description" width="800" height="415"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Code Explanation:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Import the User model to interact with user data&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Call getUsers and getUsersById methods to perform corresponding operations&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Each method calls methods from model layer. In a real-time project this would include operations performed using a ORM (Object Relationship Mapper). Find more on ORMs here : &lt;a href="https://medium.com/@rishu__2701/node-js-database-magic-exploring-the-powers-of-sequelize-orm-a22a521d9d9d"&gt;https://medium.com/@rishu__2701/node-js-database-magic-exploring-the-powers-of-sequelize-orm-a22a521d9d9d&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Step 13:&lt;/strong&gt;  Create a file name &lt;strong&gt;user.controller.js&lt;/strong&gt; under controllers folder&lt;/p&gt;

&lt;p&gt;In your controllers , you would import and use the service methods to handle HTTP requests&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F17wsym3y75gosfowwbsq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F17wsym3y75gosfowwbsq.png" width="800" height="631"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Code Explanation:&lt;/p&gt;

&lt;p&gt;-Import respective service function within the controller file, in our case &lt;strong&gt;user.service.js&lt;/strong&gt; within &lt;strong&gt;user.controller.js&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Define route handlers getAllUsers and getUserById&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Within getAllUsers we are retrieving all user data and sending it as a response with a HTTP status 200. In scenarios where database operations are involved, the data retrieval might fail. In that case, the response needs to be sent accordingly with a status 500.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;getUserById(), finds userId from request params. Find more on request params &lt;a href="https://www.geeksforgeeks.org/difference-between-req-query-and-req-params-in-express/"&gt;https://www.geeksforgeeks.org/difference-between-req-query-and-req-params-in-express/&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Send user data with status 200 on successful response&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Send 404 if User is not found&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;More on HTTP status codes here &lt;a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Status"&gt;https://developer.mozilla.org/en-US/docs/Web/HTTP/Status&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Step 14:&lt;/strong&gt;  Create a file name &lt;strong&gt;user.routes.js&lt;/strong&gt; under routes folder&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;user.routes.js&lt;/strong&gt; is typically a file where you define and configure all your application routes using Express Router. Here’s how you can structure and explain a routes.js file:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fb60lbwuyf2x9aqh5nl1z.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fb60lbwuyf2x9aqh5nl1z.png" alt="Image description" width="800" height="335"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 15:&lt;/strong&gt; Advantages of following this code pattern&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Separation of Concerns: The service layer (user.service.js) encapsulates business logic and serves as an intermediary between controllers and models.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Reusability: Services can be reused across different parts of the application, promoting code reuse and maintaining DRY (Don't Repeat Yourself) principles. In the scenarios where multiple services need to be called together, a manager file can be created (eg: user.manager.js) that imports all the required services and calls them wherever required. Manager file in turn needs to be imported in controller file.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Modularity: Each layer (models, services, controllers) has a distinct responsibility, making the application easier to understand, test, and maintain.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Mock Data: In real-world applications, you would replace the mock data and methods in the model (User.js) with actual database interaction using libraries like Mongoose, Sequelize, etc.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Step 16:&lt;/strong&gt; Mounting routes.js in app.js&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftvs6m6vfb50udj20alft.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftvs6m6vfb50udj20alft.png" alt="Image description" width="800" height="568"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In your main application file (e.g., index.js), you would integrate routes.js by mounting the router using app.use().&lt;/p&gt;

&lt;p&gt;const usersRoute = require('./routes/user.route'); Import the routes.js file.&lt;/p&gt;

&lt;p&gt;app.use('/users, routes);: Mount the router at the / users prefix. All routes defined in routes.js will be accessible under / users (e.g., / users /:id, / users /:id/likes, etc.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 17:&lt;/strong&gt; Test APIs with Postman&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzgexbuodx2iu0fwekxm6.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzgexbuodx2iu0fwekxm6.png" alt="Image description" width="800" height="544"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fli8a9v2jxmze7i64nydg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fli8a9v2jxmze7i64nydg.png" alt="Image description" width="800" height="439"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;More Resources on REST APIs&lt;/p&gt;

&lt;p&gt;HTTP Verbs -&amp;gt; &lt;a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods"&gt;https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;REST naming conventions -&amp;gt; &lt;a href="https://restfulapi.net/resource-naming/"&gt;https://restfulapi.net/resource-naming/&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;API Documentation -&amp;gt; &lt;a href="https://swagger.io/blog/api-documentation/what-is-api-documentation-and-why-it-matters/"&gt;https://swagger.io/blog/api-documentation/what-is-api-documentation-and-why-it-matters/&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Conclusion:&lt;/p&gt;

&lt;p&gt;In summary, REST APIs are essential for modern web development, providing a standardized way for clients and servers to communicate efficiently. Node.js with Express.js offers a powerful framework for creating RESTful APIs, enabling developers to build scalable and maintainable backend systems.&lt;/p&gt;

&lt;p&gt;By leveraging Node.js's non-blocking architecture and Express's simplicity, developers can quickly create robust API endpoints for various applications. Understanding these technologies ensures you can deliver efficient, secure, and adaptable backend solutions that meet current and future needs in web development.&lt;/p&gt;

&lt;p&gt;Follow for more insightful content on web development and stay updated with the latest tips and tutorials. See you next week with more valuable insights!&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>rest</category>
      <category>node</category>
      <category>express</category>
    </item>
  </channel>
</rss>
