<?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" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Victor Yakubu - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Victor Yakubu - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Fri, 05 Jun 2026 04:59:18 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/author/theAviatorCodes2/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Create a CRUD API – NodeJS and Express Project for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ An API is a technology that powers communication between software applications on the internet. API stands for Application Programming Interface, and it is basically a set of rules and protocols that define how different software can interact with ea... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/create-crud-api-project/</link>
                <guid isPermaLink="false">66ba305cf1ac6be9964fe7ac</guid>
                
                    <category>
                        <![CDATA[ api ]]>
                    </category>
                
                    <category>
                        <![CDATA[ backend ]]>
                    </category>
                
                    <category>
                        <![CDATA[ crud ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Express.js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Node.js ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Victor Yakubu ]]>
                </dc:creator>
                <pubDate>Fri, 08 Mar 2024 11:04:53 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/03/Swimm-Images-4.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>An API is a technology that powers communication between software applications on the internet. API stands for Application Programming Interface, and it is basically a set of rules and protocols that define how different software can interact with each other. </p>
<p>Imagine having two different programs: program A and program B. For these two programs to communicate together, an API is needed, and a set of rules ensure that they know what to expect when they interact with each other.</p>
<p>As a backend developer, your responsibilities involve building server-side applications, handling data storage, and providing the necessary functionalities to do all these through APIs. </p>
<p>There are <a target="_blank" href="https://blog.postman.com/different-types-of-apis/">different types of APIs</a> like REST, GraphQL, gRPC, SOAP, and WebSockets. However, when it comes to web development, one is more popular, and that is the <a target="_blank" href="https://www.freecodecamp.org/news/what-is-a-rest-api/">REST API</a>.</p>
<p>In this article, you will learn how to create a CRUD API with Node.js and Express using the REST architecture, and by the end of this article, you should have a fully functional API that is able to perform CRUD operations.</p>
<p>So, let's dive into the world of backend development with Node.js and Express and get started on our journey to building a CRUD API.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><a class="post-section-overview" href="#heading-what-is-a-crud-api">What is a CRUD API?</a></li>
<li><a class="post-section-overview" href="#heading-what-is-nodejs">What is Node.js?</a></li>
<li><a class="post-section-overview" href="#heading-why-node">Why Node?</a></li>
<li><a class="post-section-overview" href="#heading-how-to-install-nodejs">How to Install Node.js</a></li>
<li><a class="post-section-overview" href="#heading-what-is-express">What is Express?</a></li>
<li><a class="post-section-overview" href="#heading-why-do-you-need-express">Why do You Need Express?</a></li>
<li><a class="post-section-overview" href="#heading-prerequisites">Prerequisite<strong>s</strong></a></li>
<li><a class="post-section-overview" href="#heading-how-to-set-up-your-development-environment">How to Set Up Your Development Environment</a></li>
<li><a class="post-section-overview" href="#heading-how-to-set-up-a-server-for-your-crud-restful-api-with-nodejs-and-express">How to Set up a server for Your CRUD Restful API with Node.js and Express</a></li>
<li><a class="post-section-overview" href="#heading-crud-api-example">CRUD API Example</a></li>
<li><a class="post-section-overview" href="#heading-how-to-create-api-routes">How to Create API Routes</a></li>
<li><a class="post-section-overview" href="#heading-how-to-create-your-own-crud-api">How to Create Your own CRUD API</a></li>
<li><a class="post-section-overview" href="#heading-how-to-create-the-get-users-endpoint">How to Create the GET /users Endpoint</a></li>
<li><a class="post-section-overview" href="#heading-how-to-test-your-api-get-request">How to Test Your API GET Request</a></li>
<li><a class="post-section-overview" href="#heading-how-to-create-the-post-users-endpoint">How to Create the POST /users Endpoint</a></li>
<li><a class="post-section-overview" href="#heading-how-to-test-the-post-request">How to Test the POST Request</a></li>
<li><a class="post-section-overview" href="#heading-how-to-create-the-get-usersid-endpoint">How to Create the GET /users/:id Endpoint</a></li>
<li><a class="post-section-overview" href="#heading-how-to-test-the-get-request">How to Test the GET Request</a></li>
<li><a class="post-section-overview" href="#heading-how-to-create-the-delete-usersid">How to Create the DELETE /users/:id</a></li>
<li><a class="post-section-overview" href="#heading-how-to-test-the-delete-request">How to Test the DELETE Request</a></li>
<li><a class="post-section-overview" href="#heading-how-to-create-the-patch-usersid-endpoint">How to Create the PATCH /users/:id Endpoint</a></li>
<li><a class="post-section-overview" href="#heading-how-to-test-the-patch-request">How to Test the PATCH Request</a></li>
<li><a class="post-section-overview" href="#heading-wrapping-up">Wrapping UP</a></li>
</ul>
<h2 id="heading-what-is-a-crud-api">What is a CRUD API?</h2>
<p>In web development, CRUD operations are the bread and butter of backend systems. This is because they allow you to "Create", "Read", "Update", and "Delete" data through your API. </p>
<p>Here's a quick overview of the four primary HTTP methods associated with CRUD operations:</p>
<ul>
<li><strong>GET</strong>: Used for reading or retrieving data from the server.</li>
<li><strong>POST</strong>: Used for creating new data on the server.</li>
<li><strong>PUT</strong>: Used for updating existing data on the server.</li>
<li><strong>DELETE</strong>: Used for removing data from the server.</li>
</ul>
<p>Virtually every web application interacts with a database to perform these four core operations. Whether it's a social media platform, an e-commerce website, or a weather app, they all rely on creating, reading, updating, and deleting data. </p>
<p>For example, WhatsApp recently added an edit feature to the application, allowing users to make corrections to an already-sent message. That's one part of the CRUD operation in action (updating).</p>
<p>In the context of building a web API, these operations become the backbone of how your application interacts with data. Your API provides endpoints that allow client applications (like web or mobile apps) to perform these operations on the server. </p>
<p>This communication between the client and the server is the essence of web development, and understanding how to create a CRUD API is a crucial skill for a web developer.</p>
<h2 id="heading-what-is-nodejs">What is Node.js?</h2>
<p>Node.js is an open-source and cross-platform runtime environment for executing JavaScript code outside of a browser. Quite often, we use it to build back-end services, also called APIs. Node is ideal for building highly scalable, data-intensive and real-time back-end services that power our client applications</p>
<h2 id="heading-why-node">Why Node?</h2>
<ul>
<li>It is one of the most popular choices for building the backend.</li>
<li>You get to write JavaScript across your entire stack, making it easier to transition from either a frontend developer to a backend developer and vice versa.</li>
<li>It allows for easy scaling of applications, making it a good choice for large-scale professional projects.</li>
<li>It is fast and non-blocking. This is because of the asynchronous event-driven nature of Node.js.</li>
<li>Node.js has a vibrant community and a rich ecosystem of packages and libraries.</li>
</ul>
<h2 id="heading-how-to-install-nodejs">How to Install Node.js</h2>
<p>Installation steps:</p>
<ol>
<li>Download the Mac/Windows installer from the <a target="_blank" href="https://nodejs.org/en/download">Node.js website</a>.</li>
<li>Choose the Long-Term Support (LTS) version that’s shown on the left</li>
<li>After downloading, install/run the installer, and then follow the prompts. (You will have to click the NEXT button a bunch of times and accept the default installation settings</li>
<li>To confirm that Node has been successfully installed, open your terminal and run the command. (For Windows, you might need to restart your command before running it.)</li>
</ol>
<pre><code>node –version
</code></pre><h2 id="heading-what-is-express">What is Express?</h2>
<p>Express is a fast, unopinionated, and minimalist web backend or server-side web framework for Node.js. Basically, it gives you the ability to build your APIs how you want them, with less code.</p>
<p>It is a framework built on top of Node.js that allows you to create your Backend with ease. You can use Express in combination with frontend frameworks like React, Angular, or Vue to build full-stack applications.</p>
<h2 id="heading-why-do-you-need-express">Why do You Need Express?</h2>
<ul>
<li>It makes building web applications with Node.js much easier.</li>
<li>It is extremely light, fast and free.</li>
<li>It is used for both server-rendered apps as well as API/Microservices.</li>
<li>It is the most popular Node.</li>
<li>It gives you full control over requests and responses.</li>
</ul>
<h2 id="heading-prerequisites">Prerequisite<strong>s</strong></h2>
<p>To follow along, you'll need to have the following:</p>
<ul>
<li>Basic knowledge of JavaScript</li>
<li>Download and install <a target="_blank" href="https://nodejs.org/en">Node.js</a> and <a target="_blank" href="https://www.postman.com/downloads/">Postman</a> on your computer</li>
</ul>
<p>See the complete code for this tutorial on <a target="_blank" href="https://github.com/Aviatorscode2/crud-api-tutorial">Github</a>.</p>
<h2 id="heading-how-to-set-up-your-development-environment">How to Set Up Your Development Environment</h2>
<p>Before diving into creating your API, let's go through the process of creating a basic server on your local computer. </p>
<p>Here are the steps to follow:</p>
<h3 id="heading-step-1-create-directory">Step #1 – Create Directory</h3>
<p>Create a directory/folder on your computer. Open the folder in a code editor</p>
<h3 id="heading-step-2-create-indexjs-file">Step #2 – Create index.js File</h3>
<p>Create an <strong>index.js</strong> file inside the folder using this command:</p>
<pre><code>touch index.js
</code></pre><h3 id="heading-step-3-initialize-npm">Step #3 – Initialize NPM</h3>
<p>Initialize NPM inside the folder by running this command in your terminal:</p>
<pre><code>npm init -y
</code></pre><p>The command will create a <strong>package.json</strong> file with default values.</p>
<h3 id="heading-step-5-install-express">Step #5 – Install Express</h3>
<p>Use the command below to install Express.js</p>
<pre><code>npm install express
</code></pre><p>After installing Express, go to the <strong>package.json</strong> file and include <strong>“type”: “module”</strong>. This declaration will tell Node that this project will be using <a target="_blank" href="https://nodejs.org/api/packages.html#type">ES6 module syntax</a> (import/export) instead of common.js, which is the default in Node.  </p>
<p><img src="https://lh7-us.googleusercontent.com/s0sHrHSK7ulqOU4Ddw6WzER6waGEGaCxV26mk-ieuqDVKYBZSKlJ1aDW8WXbCOlfzC1xcW8lXh1-HVSNnYUXYM3MRmmy0N-6uQh-J3qDnjHtxB5atRbJQ-cxR1AWzLTa9RTwv_cXNXpNGz3lbSBHejM" alt="Image" width="600" height="400" loading="lazy">
<em>package.json file with <code>type:module</code></em></p>
<h2 id="heading-how-to-set-up-a-server-for-your-crud-restful-api-with-nodejs-and-express">How to Set up a server for Your CRUD Restful API with Node.js and Express</h2>
<p>To create a CRUD <a target="_blank" href="https://www.freecodecamp.org/news/what-is-rest-rest-api-definition-for-beginners/#:~:text=An%20API%20that%20complies%20with%20some%20or%20all%20of%20the%20six%20guiding%20constraints%20of%20REST%20is%20considered%20to%20be%20RESTful.">restful</a> API, you first need to set up your server. You can do this by following these steps:</p>
<h3 id="heading-step-1-write-your-server-application-code-inside-the-indexjs-file">Step #1 – Write your Server Application Code inside the index.js file</h3>
<p>Basically, a server code will look like this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> express <span class="hljs-keyword">from</span> <span class="hljs-string">'express'</span>;
<span class="hljs-keyword">import</span> bodyParser <span class="hljs-keyword">from</span> ‘body-parser

<span class="hljs-keyword">const</span> app = express();
<span class="hljs-keyword">const</span> PORT = <span class="hljs-number">5000</span>

app.use(bodyParser.json());

app.listen(PORT, <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Server running on port: http://localhost:<span class="hljs-subst">${PORT}</span>`</span>));
</code></pre>
<p>Here's an explanation for the code above:</p>
<ul>
<li>In the first line, we imported <code>express</code> from the Express module that we installed.</li>
<li>The <code>bodyParser</code> comes with Express, and it allows us to take in the incoming POST request body.</li>
<li>Next, we created an <code>app</code> using the <code>express</code> object.</li>
<li>We then specified the port for the application – it was set to <strong>5000</strong> (if you get an error using this port, it might be that the port is currently being used by a different app, so you can either change your port or stop the other app from using the port).</li>
<li>Next, we specified that JSON data will be used in the application.</li>
<li>Once that was created, we used the <code>listen</code> method on the <code>app</code> to make our application listen for incoming requests. The method accepts two things: the <strong>PORT</strong>, which is where we would be listening for requests from our client side, and a callback function that will be triggered when our server is set up.</li>
</ul>
<h3 id="heading-step-2-start-the-server">Step #2 – Start the Server</h3>
<p>Now you can start your server by running this command. If you used a different file, replace index.js with the file name where the server is located.</p>
<pre><code>node index.js
</code></pre><p>Now your server should be running on <strong>port 5000</strong>. You can verify that your server is running on your terminal</p>
<h3 id="heading-step-3-install-nodemon-optional">Step #3 – Install Nodemon (Optional)</h3>
<p>At the moment, anytime you make changes to your server file, you will need to restart the server before your changes can reflect (you can try it and see). So to take care of this challenge, you can use Nodemon. Run the command to install it:</p>
<pre><code>npm install nodemon
</code></pre><p>To use Nodemon, head over to your <strong>package.json</strong> file and set up a script. Replace your start script with this instead:</p>
<pre><code><span class="hljs-string">"start"</span>: <span class="hljs-string">"nodemon index.js"</span>
</code></pre><p>Note that <strong>index.js</strong> is the file where the server code is written.</p>
<p>Now you can start your server by running this command:</p>
<pre><code>npm start
</code></pre><p>With this code, we've set up a server that listens on port 5000 and prints a message when it starts. But this is just the beginning because our server needs to do much more. </p>
<p>Let's explore how to handle API requests next.</p>
<h2 id="heading-crud-api-example">CRUD API Example</h2>
<p>Let's start by defining the API routes for each CRUD operation. These routes will serve as the entry points for your API, and they will map to specific actions we want to perform on our data. </p>
<p>In our case, these actions are creating, reading, updating, and deleting data.</p>
<h2 id="heading-how-to-create-api-routes">How to Create API Routes</h2>
<p>When the port (<a target="_blank" href="http://localhost:5000/">http://localhost:5000/</a>) is opened in a browser, you will get an error.</p>
<p><img src="https://lh7-us.googleusercontent.com/p-3qnXzvHDxcsbhpYXO4VMopivQMhqgSPwSTXXDQJW_2GRhFFvkpL8JitNShGcrjyQiMx87ZwkK_4iEbs3JieTdRJQ13Q94O0hV7U9mwOpcm9ET7Yngb2TXQpItUrpepYzeXzg4rZMGdnxonhMREHAo" alt="Image" width="600" height="400" loading="lazy">
<em>localhost:5000 in the browser without any routes</em></p>
<p>This is because Node.js and Express are all about routing, and we don't any routes yet. </p>
<p>You can define API routes using the <code>app.get()</code>, <code>app.post()</code>, <code>app.put()</code>, and <code>app.delete()</code> methods in your Express application (in the <strong>index.js</strong> file). </p>
<p>Here's how to create a route to handle GET requests using the <code>app.get()</code> function:</p>
<pre><code>app.get(<span class="hljs-string">'/'</span>, (req, res)
</code></pre><p>The <code>app.get()</code> function accepts two parameters. The first is used to specify the path (in this case, it is '/'). </p>
<p>The next parameter is a callback function where you define what happens when the GET request is called. The function also has <a target="_blank" href="https://www.freecodecamp.org/news/express-explained-with-examples-installation-routing-middleware-and-more/">two parameters</a>: the request body (<code>req</code>), which can contain information such as the request query string, parameters, body, and HTTP headers. While the response object (<code>res</code>) contains the information you want to send </p>
<p>Here is the complete code:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> express <span class="hljs-keyword">from</span> <span class="hljs-string">'express'</span>;
<span class="hljs-keyword">import</span> bodyParser <span class="hljs-keyword">from</span> <span class="hljs-string">'body-parser'</span>
<span class="hljs-keyword">const</span> app = express();

<span class="hljs-keyword">const</span> PORT = <span class="hljs-number">5000</span>;

app.use(bodyParser.json());

app.get(<span class="hljs-string">'/'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'[GET ROUTE]'</span>);
    res.send(<span class="hljs-string">'HELLO FROM HOMEPAGE'</span>);
})

app.listen(PORT, <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Server running on port: http://localhost:<span class="hljs-subst">${PORT}</span>`</span>));
</code></pre>
<p>When you head back to <a target="_blank" href="http://localhost:5000/">http://localhost:5000/</a> and refresh it, you shouldn’t get an error anymore.</p>
<p><img src="https://lh7-us.googleusercontent.com/6289p5Vl_k4v2ULLd5iUVCpr-sykpbcEytcHsqoJZTB4MgWgDEfVuH1_4aTt0w9ThAhFNCn_rMrlwNFB2hfgOKWQ3znH3MHnHRxh0sd1czb_ntBHMIWS6HtAIo3yuCgDEFK7RVFGvTel0s89T3qTKjc" alt="Image" width="600" height="400" loading="lazy">
<em>localhost:5000 in the browser with GET route</em></p>
<h2 id="heading-how-to-create-your-own-crud-api">How to Create Your own CRUD API</h2>
<p>For this API, you will be handling a set of users. Handling users in a database is a great example because it is a common use case in most applications. </p>
<p>Here are the API endpoints you will be creating:</p>
<ol>
<li>GET /users - find all users</li>
<li>POST /users - creates a user</li>
<li>GET /users/:id - finds a specific user</li>
<li>DELETE /users/:id - deletes a specific user</li>
<li>PATCH /users/:id - updates a specific user.</li>
</ol>
<h3 id="heading-how-to-create-the-get-users-endpoint">How to Create the GET /users Endpoint</h3>
<p>Reading data is one of the most common operations in an API. In this example, you will be getting the list of all the users in your mock database. This information will be presented in JSON format.</p>
<p>To define a route to retrieve users' data from the database, follow these steps:</p>
<ul>
<li>Create a new folder called routes</li>
<li>Create a new file called <strong>users.j</strong>s inside the routes folder.</li>
<li>Write the code to set up the GET router.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> express <span class="hljs-keyword">from</span> <span class="hljs-string">'express'</span>;
<span class="hljs-keyword">const</span> router = express.Router();

<span class="hljs-comment">// Mock database</span>
<span class="hljs-keyword">const</span> users = [
  {
    <span class="hljs-attr">first_name</span>: <span class="hljs-string">'John'</span>,
    <span class="hljs-attr">last_name</span>: <span class="hljs-string">'Doe'</span>,
    <span class="hljs-attr">email</span>: <span class="hljs-string">'johndoe@example.com'</span>,
  },
  {
    <span class="hljs-attr">first_name</span>: <span class="hljs-string">'Alice'</span>,
    <span class="hljs-attr">last_name</span>: <span class="hljs-string">'Smith'</span>,
    <span class="hljs-attr">email</span>: <span class="hljs-string">'alicesmith@example.com'</span>,
  },
];

<span class="hljs-comment">// Getting the list of users from the mock database</span>
router.get(<span class="hljs-string">'/'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
    res.send(users);
})

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> router
</code></pre>
<p>In this code snippet:</p>
<ul>
<li><code>import express from 'express';</code> imports the Express.js framework</li>
<li><code>const router = express.Router();</code> creates a fresh router instance, stored in the variable router.</li>
<li>The <code>users</code> variable serves as the mock database containing an array of users.</li>
<li>The <code>router.get()</code> function sets up a route that responds to HTTP GET requests.</li>
<li>The second part of the code <code>(req, res) =&gt; { ... }</code> is a callback function. It gets executed when a request is made to the GET route.</li>
<li>Inside the callback function, we used <code>res.send(users)</code> to send a response back to the client. In this example, we're sending the <code>users</code> variable as the response. So when a user hits the GET URL, the server responds by sending the data inside the <code>users</code> variable in JSON format to the client.</li>
</ul>
<p>Save your changes in the <strong>users.js</strong> file. Then do the following in the <strong>index.js</strong> file:</p>
<p>import your user routes from <strong>user.js</strong>:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> userRoutes <span class="hljs-keyword">from</span> <span class="hljs-string">'./routes/users.js'</span>
</code></pre>
<p>Use the <code>app.use</code> method, and specify the path and router handler:</p>
<pre><code class="lang-javascript">app.use(<span class="hljs-string">'/users'</span>, userRoutes);
</code></pre>
<p>When a user visits <a target="_blank" href="http://localhost:5000/users">http://localhost:5000/users</a>, the router is triggered. It effectively acts as a filter, determining when a specific set of routes should be applied.</p>
<p>Here is the complete code for the <strong>index.js</strong> file:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> express <span class="hljs-keyword">from</span> <span class="hljs-string">'express'</span>;
<span class="hljs-keyword">import</span> bodyParser <span class="hljs-keyword">from</span> <span class="hljs-string">'body-parser'</span>
<span class="hljs-keyword">const</span> app = express();
<span class="hljs-keyword">import</span> userRoutes <span class="hljs-keyword">from</span> <span class="hljs-string">'./routes/users.js'</span>

<span class="hljs-keyword">const</span> PORT = <span class="hljs-number">5000</span>;

app.use(bodyParser.json());

app.use(<span class="hljs-string">'/users'</span>, userRoutes);

app.get(<span class="hljs-string">'/'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> res.send(<span class="hljs-string">'HELLO FROM HOMEPAGE'</span>))

app.get(<span class="hljs-string">'/'</span>, (req, res));

app.listen(PORT, <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Server running on port: http://localhost:<span class="hljs-subst">${PORT}</span>`</span>));
</code></pre>
<h4 id="heading-how-to-test-your-api-get-request"><strong>How to Test Your API GET Request</strong></h4>
<p>You can use either a browser (browsers can only be used to perform GET requests) or Postman to test the GET request. </p>
<p>So copy your API URL, <a target="_blank" href="http://localhost:5000/users">http://localhost:5000/users</a>, and paste it either on Postman or in your browser. If you are using Postman, you will first need to make a GET request, then paste your API URL, and then click on send. After that, you will see the list of users in your Postman console.</p>
<p><img src="https://lh7-us.googleusercontent.com/XBhjewUFTBvBhc2larsYwqzS3-RHp7qFBrO4lvScf91EUFO5TEgt83iU48h9ArDK3EbrPwdS7_-WkI51JkDUHH4v2U9pWXdYMSbKeCpQrYRunvhuvAIAadzcAyj8y0hojjxs1CIlAo7TigoTJrM3y5c" alt="Image" width="600" height="400" loading="lazy">
<em>postman GET route test</em></p>
<h3 id="heading-how-to-create-the-post-users-endpoint">How to Create the POST /users Endpoint</h3>
<p>You can use the POST request to add data to your database. It accepts input from the client and stores it in the database. To create data in our API, we'll define a route that accepts POST requests and saves the data to the mock database you have set up. </p>
<p>But before that, you'll need the UUID package. Use this command to install it:</p>
<pre><code>npm install uuid
</code></pre><p>This package will help generate a unique ID for each user you will be creating. This will be useful when you are implementing the GET, DELETE, and PATCH user by ID requests, where you will need a way to identify a specific user.</p>
<p>So in the <strong>users.js</strong> file, do the following:</p>
<p>Import the <code>uuid</code> package:</p>
<pre><code><span class="hljs-keyword">import</span> { v4 <span class="hljs-keyword">as</span> uuidv4 } <span class="hljs-keyword">from</span> <span class="hljs-string">'uuid'</span>;
</code></pre><p>Secondly, you'll have to implement the code for the POST request. </p>
<p>Here is what it looks like:</p>
<pre><code class="lang-javascript">router.post(<span class="hljs-string">'/'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> user = req.body;

    users.push({ ...user, <span class="hljs-attr">id</span>: uuidv4() });

    res.send(<span class="hljs-string">`<span class="hljs-subst">${user.first_name}</span> has been added to the Database`</span>);
})
</code></pre>
<p>In the code snippet:</p>
<ul>
<li>The <code>router.post()</code> function sets up a route that responds to HTTP POST requests. This means that when a client sends a POST request to the root URL of your application, this route will be triggered.</li>
<li>Within the callback function <code>(req, res) =&gt; { ... }</code>, we access the <code>req</code> object, which represents the incoming request made by the client. Specifically, we're interested in the <code>req.body</code> property. This property contains the data (first name, last name, and email) that the client will send as part of the POST request's body.</li>
<li>With <code>const user = req.body</code> we extract this data from <code>req.body</code> and store it in the <code>user</code> variable.</li>
<li>Next, we added the <code>user</code> data to an array called <code>users</code>. To ensure each user has a unique identifier, we generate a universally unique identifier (UUID) using a function like <code>uuidv4()</code> and include it as id in the user object. This helps in keeping user records distinct and identifiable.</li>
<li>Finally, we used <code>res.send()</code> to send a response back to the client. In this case, we're sending a simple message notifying the client that the user has been successfully added to the database. The message includes the user's first name for a personalized touch.</li>
</ul>
<p>Here is the complete code</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> express <span class="hljs-keyword">from</span> <span class="hljs-string">'express'</span>;
<span class="hljs-keyword">import</span> { v4 <span class="hljs-keyword">as</span> uuidv4 } <span class="hljs-keyword">from</span> <span class="hljs-string">'uuid'</span>;

<span class="hljs-keyword">const</span> router = express.Router();

<span class="hljs-keyword">const</span> users = [];

<span class="hljs-comment">// Adding users to our mock database</span>

router.post(<span class="hljs-string">'/'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> user = req.body;

    users.push({ ...user, <span class="hljs-attr">id</span>: uuidv4() });

    res.send(<span class="hljs-string">`<span class="hljs-subst">${user.first_name}</span> has been added to the Database`</span>);
})  

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> router
</code></pre>
<h4 id="heading-how-to-test-the-post-request"><strong>How to Test the POST Request</strong></h4>
<p>Here are the steps to follow to make a POST request on Postman:</p>
<ul>
<li>Go to Postman</li>
<li>Open a new request tab</li>
<li>Select "POST" from the list of available HTTP methods</li>
<li>In the URL field, enter the full URL where you want to send the POST request (<a target="_blank" href="http://localhost:5000/users">http://localhost:5000/users</a>)</li>
<li>Click on the "Body" tab in the request window.</li>
<li>Choose the format in which you want to send your POST data (choose JSON).</li>
<li>Enter the data you want to send in the request body. This data should match the format expected by the server.</li>
<li>Finally, click on “Send”  </li>
</ul>
<p><img src="https://lh7-us.googleusercontent.com/olNqMdggCcvhUotN9ospAjg8r7t-HE_3yUqGrEkf_dKnCGTwFiKWQJB3x4dccUbHPlYbP-j8S7a2xBG3TpMvceVdmz_nC8zRtaRQzfeknyyo-OQJDwuSFZJkWPiQctDkoTYfZCsVnE1ljQN96Hxow54" alt="Image" width="600" height="400" loading="lazy">
<em>postman POST route test</em></p>
<p>If it is successful, you will get a response saying, “Daanny has been added to the database."</p>
<p>To confirm if it has been added, make a GET request, and you should see the new user added to your database. (Note: This user information will be lost when your server restarts since it’s not saved to an actual database).</p>
<p><img src="https://lh7-us.googleusercontent.com/cHmJ3hcsMb5Vnj9zh_kSdqBMRrgtR1pQJ3-_DgHgukwdtyLrnG5AN0jyL4gGtzyTYUJj4w_ENO6ZqVsMZLqdnRytOgP4tR5A2B2T_TnDHNbRDEb9JAGF7SmTwVVwBczzg02JmLfWAucyeyMlnPs1Ehg" alt="Image" width="600" height="400" loading="lazy">
<em>postman GET route test</em></p>
<h3 id="heading-how-to-create-the-get-usersid-endpoint">How to Create the GET /users/:id Endpoint</h3>
<p>Fetching specific data based on a unique identifier, such as a user ID, is a common operation. It's often essential for building features like user profiles or retrieving individual records from a database. </p>
<p>In this section, you’ll explore how to use this endpoint (users/:id) to retrieve user information based on a provided user ID. </p>
<p>Let's get started!</p>
<pre><code class="lang-javascript">router.get(<span class="hljs-string">'/:id'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
    <span class="hljs-keyword">const</span> { id } = req.params;

    <span class="hljs-keyword">const</span> foundUser = users.find(<span class="hljs-function">(<span class="hljs-params">user</span>) =&gt;</span> user.id === id)

    res.send(foundUser)
});
</code></pre>
<p>Here's what this code snippet does:</p>
<ul>
<li>The <code>router.get()</code> function sets up a route that responds to HTTP GET requests. In this example, we've defined a route with ('/:id'). The :id part is a route parameter, which allows us to capture a dynamic value from the URL. In this case, it represents the user ID we want to retrieve.</li>
<li>Within the callback function <code>(req, res) =&gt; { ... }</code>, we can access the <code>req</code> object, which represents the incoming request made by the client. Specifically, we're interested in <code>req.params</code>, which holds the values of route parameters. In this case, we destructure <code>id</code> from <code>req.params</code>, effectively extracting the user ID from the URL. For example, if a client makes a GET request to /users/123, the id will be '123'.</li>
<li>We used the <code>.find()</code> method to search through this data based on the user ID (id) captured from the URL. This method attempts to find a user whose ID matches the provided id.</li>
<li>Once we located the user data (if it exists), we send it as the response using <code>res.send(foundUser)</code>. The <code>foundUser</code> variable contains the user object that matches the requested ID.</li>
</ul>
<h4 id="heading-how-to-test-the-get-request"><strong>How to Test the GET Request</strong></h4>
<p>In testing the API, follow these steps:</p>
<ul>
<li>Go to your POST request tab and make as many requests as you want to add a new user to the database.</li>
<li>Go to your GET request tab and make a request to see the list of users you have added</li>
</ul>
<p><img src="https://lh7-us.googleusercontent.com/qEuvm-1QKHvGmFCmru5dF2b9JSW5ua_dMcovZaKFZL_NChfSQqaazX4QvvSrSkjMzTO9Yqon5zhsZ5ZZwrWO0WifthlOKfboojC6ws8Fju2HK5TcE1oLvZZhOaO5xljRIUvYt_oun_NsIH13sq2Yf0o" alt="Image" width="600" height="400" loading="lazy">
<em>postman GET route test</em></p>
<ul>
<li>Copy the id of any of the users on the list</li>
<li>Create a new GET request tab, copy in the base API URL, and add the id of any of the users to it. It should be in a format like this: <a target="_blank" href="http://localhost:5000/users/734a9e75-b3f5-415f-82fb-79b4fdf1a593">http://localhost:5000/users/734a9e75-b3f5-415f-82fb-79b4fdf1a593</a></li>
<li>Click on “Send”. If it’s successful, you will see the user information of the user id you used for the request</li>
</ul>
<p><img src="https://lh7-us.googleusercontent.com/ui9cj6HDXIifMjzlnICvnzgIGOssvRbGeCrlos2DXG541b4r9Dsn0mVrXZBfyCwvO6gh3yovrbsDD1I7EU0-5j7r3fRIrQ4XFX1QR-vlFJlXuXb1Ht753re7ZDf2cC7VyPyLgee6a6gZmwjnkCb8RI0" alt="Image" width="600" height="400" loading="lazy">
<em>postman GET route test</em></p>
<h3 id="heading-how-to-create-the-delete-usersid">How to Create the DELETE /users/:id</h3>
<p>Sometimes, it's necessary to remove user accounts or specific records from a database for various reasons, such as account deactivation. </p>
<p>Here, you will explore how to use this endpoint to delete user data based on a provided user ID.</p>
<p>To delete data, we'll define a route that accepts DELETE requests and removes the data from the database.</p>
<p>See the code to delete a user from a database below</p>
<pre><code class="lang-javascript">router.delete(<span class="hljs-string">'/:id'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> { id } = req.params;

  users = users.filter(<span class="hljs-function">(<span class="hljs-params">user</span>) =&gt;</span> user.id !== id)

  res.send(<span class="hljs-string">`<span class="hljs-subst">${id}</span> deleted successfully from database`</span>);
});
</code></pre>
<p>Here's what this code does:</p>
<ul>
<li>The <code>router.delete()</code> function sets up a route that responds to HTTP DELETE requests. In this example, we've defined a route with ('/:id'), where :id is a route parameter. It captures a dynamic value from the URL, representing the user ID we want to delete.</li>
<li>In the callback function <code>(req, res) =&gt; { ... }</code>, we can access the <code>req</code> object, which represents the incoming request made by the client. Specifically, we're interested in <code>req.params</code>, which holds the values of route parameters. Here, we destructure id from <code>req.params</code>, extracting the user ID from the URL. For instance, if a client sends a DELETE request to /users/123, id will be '123'.</li>
<li>Assuming that we have an array or database (users) containing user data, we employ the <code>.filter()</code> method to create a new array that excludes the user with the matching ID (id). This effectively removes the user from the data store.</li>
<li>After successfully deleting the user, we send a response back to the client using <code>res.send()</code>. The response contains a message confirming the deletion, including the user's ID that was deleted from the database.</li>
</ul>
<h4 id="heading-how-to-test-the-delete-request"><strong>How to Test the DELETE Request</strong></h4>
<p>Here are the steps to delete a user from the database on Postman:</p>
<ul>
<li>Go to Postman</li>
<li>Open a new request tab</li>
<li>Select "DELETE" from the list of available HTTP methods</li>
<li>Enter the URL. It should contain the id of the user you want to delete (for example: <a target="_blank" href="http://localhost:5000/users/734a9e75-b3f5-415f-82fb-79b4fdf1a593">http://localhost:5000/users/734a9e75-b3f5-415f-82fb-79b4fdf1a593</a>). If you don’t have a user in your database, you will need to create one and copy the id.</li>
<li>Click on “Send”.  </li>
</ul>
<p><img src="https://lh7-us.googleusercontent.com/bTO6dcTaujyxm7ruPcyCJTzMfZemFop1oqU803Fif2kCeq1Z2q3uB1-JHB1aK4-ePIimPvb1LBYuty8_YFd7xP_i8UVhFZewWHlmwKy3MlWssMWtdaBnXtCkyB8NZebDnldJzRXc_v0Fs7MS4rZJq_g" alt="Image" width="600" height="400" loading="lazy">
<em>postman DELETE route test</em></p>
<p><img src="https://lh7-us.googleusercontent.com/B9YHqAtEyg1f0O0CAojNJDXjK212LCxFodc9Ld3j04bdZsK9R5qHExSxaKGCAqgI0W79jHJ2bN3l9GkVgB3DYAd192zB9LzThvcAZJFuXoBO5JUqcUKWyBWcc6q4KirQA4B6Hi6t1NN3eU8e-dH10pY" alt="Image" width="600" height="400" loading="lazy">
<em>postman DELETE route test</em></p>
<h3 id="heading-how-to-create-the-patch-usersid-endpoint">How to Create the PATCH /users/:id Endpoint</h3>
<p>There are times when you don't need to update an entire resource or object. Instead, you'd want to make partial modifications or adjustments. This is where the HTTP PATCH request comes into play.</p>
<p>For example, after creating a new user, you can change either the first name, last name, or email of that user using the PATCH request. Let’s see how to do that.</p>
<pre><code class="lang-javascript">router.patch(<span class="hljs-string">'/:id'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> { id } = req.params;

  <span class="hljs-keyword">const</span> { first_name, last_name, email} = req.body;

  <span class="hljs-keyword">const</span> user = users.find(<span class="hljs-function">(<span class="hljs-params">user</span>) =&gt;</span> user.id === id)

  <span class="hljs-keyword">if</span>(first_name) user.first_name = first_name;
  <span class="hljs-keyword">if</span>(last_name) user.last_name = last_name;
  <span class="hljs-keyword">if</span>(email) user.email = email;

  res.send(<span class="hljs-string">`User with the <span class="hljs-subst">${id}</span> has been updated`</span>)

});
</code></pre>
<p>Here's what this code snippet accomplishes:</p>
<ul>
<li>The <code>router.patch()</code> function sets up a route that responds to HTTP PATCH requests. In this example, we've defined a route with ('/:id'), where :id is a route parameter. It captures the dynamic value from the URL, representing the user ID we want to update.</li>
<li>Within the callback function <code>(req, res) =&gt; { ... }</code>, we can access the <code>req</code> object, which represents the incoming request made by the client. Specifically, we're interested in <code>req.params</code>, which hold the values of route parameters (id in this case), and <code>req.body</code>, which contains the data to be updated.</li>
<li>Next, we used <code>.find()</code> to locate the user object with the matching ID (id). Once found, we can proceed to modify the user's data based on the content of <code>req.body</code>. We also checked if first_name, last_name, or email properties exist in <code>req.body</code>. If they do, we can update the corresponding properties of the user object with the new values. This allows us to make selective changes to the user's data without affecting other attributes.</li>
<li>After successfully applying the requested modifications, we send a response back to the client using <code>res.send()</code>. The response includes a message confirming the successful update of the user data, along with the user's ID.</li>
</ul>
<h4 id="heading-how-to-test-the-patch-request"><strong>How to Test the PATCH Request</strong></h4>
<p>Follow these steps to make a PATCH request in Postman:</p>
<ul>
<li>Go to Postman</li>
<li>Open a new request tab</li>
<li>Select "PATCH" from the list of available HTTP methods</li>
<li>Enter URL; the URL will contain the id of the user you want to delete (for example: <a target="_blank" href="http://localhost:5000/users/734a9e75-b3f5-415f-82fb-79b4fdf1a593">http://localhost:5000/users/734a9e75-b3f5-415f-82fb-79b4fdf1a593</a>). If you don’t have a user in your database, you will need to create one and copy the id.</li>
<li>Click on the "Body" tab in the request window and choose the format in which you want to send your PATCH data (for example: JSON, form-data, x-www-form-urlencoded).</li>
<li>Enter the data you want to send in the request body. This data should only include the specific changes you want to make to the resource.</li>
<li>Then click the "Send" button. Postman will send the PATCH request to the specified URL with the provided data.</li>
</ul>
<p><img src="https://lh7-us.googleusercontent.com/K1OH_u-2DOJbkMqlQ3uJow9XNKh0iOmE8fedCCspUiQIHcvm-DmIorFvZcApoDWGSK4YMkFR7RtcHBmzMZaJUyXy7SMDJWxH_PDLFmugGPNQDmKzM6HE3tPOBQZaS1388bZzLlmcTThQa_wy1ZPrm1g" alt="Image" width="600" height="400" loading="lazy">
<em>postman PATCH route test</em></p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>APIs are the linchpin connecting various software components and enabling them to work together seamlessly. They allow them to communicate, share data, and perform tasks. In the context of web development, APIs enable the web to function as we know it today.</p>
<p>In this tutorial, we explored backend development by creating a CRUD API with Node.js and Express. We covered various concepts, like how to set up a development environment, create a server with Express and Node.js, and most importantly, how to handle CRUD operations and test your API using Postman.</p>
<p>While we've covered fundamental aspects of API creation in this tutorial, there is still a vast landscape of knowledge to explore as regards to APIs. These include how to secure your API by adding authentication, how to use middleware, database interaction, API deployment, and a lot more.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use IndexedDB – Database Guide for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ The modern browser has given us a number of options when it comes to storing data on the client-side. Aside from storing data, browser databases allow us to retrieve that data.  Based on your application's needs, you can choose from the different bro... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-indexeddb-works-for-beginners/</link>
                <guid isPermaLink="false">66ba305e941c8586b8c21fd7</guid>
                
                    <category>
                        <![CDATA[ beginners guide ]]>
                    </category>
                
                    <category>
                        <![CDATA[ database ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Victor Yakubu ]]>
                </dc:creator>
                <pubDate>Thu, 08 Sep 2022 16:23:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/09/Colorful-Minimalist-Shapes-Internal-Pitch-Deck-Talking-Presentation-1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>The modern browser has given us a number of options when it comes to storing data on the client-side. Aside from storing data, browser databases allow us to retrieve that data. </p>
<p>Based on your application's needs, you can choose from the different browser storage options out there to enhance your users' experience when they use your applications. </p>
<p>One of these browser storage options is IndexedDB. I used IndexedDB for the first time a couple of months ago. Before using it, I went through articles and videos on various implementations of it. So I thought it would be nice to write about it based on my understanding of how it works. </p>
<p>So basically in this article, I will be talking about what IndexedDB is, its advantages, and how it works.</p>
<h2 id="heading-what-is-a-database">What is a Database?</h2>
<p>These days, data are everywhere. Data can be any information such as your age, location, what you've recently purchased from an online site, and so on. Data can be in the form of videos, images, files or even text.  </p>
<p>Companies need to be able to store and process that data effectively, and they use databases for this purpose.</p>
<p>Now, a database is simply where you store data – it's that simple. So if you open an excel sheet, for example, and populate it with data, that is considered a database. </p>
<p>The purpose of storing data in a database is to make it easy to access. This lets you modify it, protect it, and also analyze it to get as many insights as you can.</p>
<h2 id="heading-types-of-databases">Types of Databases</h2>
<p>There are mainly two types of database out there. Depending on your needs you'll want to try both out on you journey:</p>
<h3 id="heading-relational-databases">Relational Databases</h3>
<p>In a relational database, data is stored in a collection of tables. These tables are connected to one another. </p>
<p>Examples of relational databases include Oracle, PostgreSQL, MySQL, Microsoft SQL Server, and so on.</p>
<h3 id="heading-non-relational-databases">Non-Relational Databases</h3>
<p>In a non-relational database, data is stored in collections. There are no tables, columns, or rows and the data are not connected to one another. </p>
<p>Under non-relational databases, there are different categories: key-value databases, Document Databases, graph databases, wide column databases, search engine databases, and more.</p>
<p>Examples of non-relational database include Redis, MongoDB, Neo4j, Cassandra, and others, our very own IndexedDB is also a non-relational database.</p>
<p>In this article we won't cover databases themselves in-depth, as it is not the primary purpose. But <a target="_blank" href="https://www.freecodecamp.org/news/author/dionysia/">Dionysia Lemonaki</a> has a more detailed article on relational and non-relational databases which you can check out <a target="_blank" href="https://www.freecodecamp.org/news/relational-vs-nonrelational-databases-difference-between-sql-db-and-nosql-db/">here</a> to learn more.</p>
<p>It's exciting to know that IndexedDB, which we will be talking about here, is a database that is available on all modern browsers. But, IndexedDB is not the only browser storage option available to you. There's also <a target="_blank" href="https://www.freecodecamp.org/news/how-leverage-local-storage-to-build-lightning-fast-apps-4e8218134e0c/">local storage</a>, <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage">session storage</a>, <a target="_blank" href="https://www.freecodecamp.org/news/everything-you-need-to-know-about-cookies-for-web-development/">cookies</a>, <a target="_blank" href="https://www.w3.org/TR/webdatabase/">Web SQL</a>, and <a target="_blank" href="https://www.freecodecamp.org/news/web-caching-explained-by-buying-milk-at-the-supermarket-2ba6133ca4ed/">cache storage</a>. </p>
<p>You might already be familiar with these options, but if you are not, I encourage you to read more about them. </p>
<h2 id="heading-what-is-browser-storage-how-is-it-different-from-server-storage">What is Browser Storage? How is it Different from Server Storage?</h2>
<p>Browser storage is also referred to as client-side storage. It simply means storage that's located on a user's browser.</p>
<p>Just like server-side storage (which allows you to store data on a database called the backend) where you are able to communicate with the database using lines of code, client-side storage uses the same principle. </p>
<p>But keep in mind that client-side storage is not a substitute for server-side storage. Client-side storage a mainly used to enhance the user's experience. </p>
<p>A simple example is when you log in to a platform for the first time. The server-side storage handles authentication and necessary authorizations, and the client-side storage makes it possible for you to visit that platform after a few hours and continue from your previous state without having to send a request to the backend.</p>
<p>And then, whenever you need to log in after some time, the client-side storage saves your login details, and auto-fills them in. All that will be required from you is to click the login button.</p>
<p>Server-side can be written and accessed using any number of programming languages depending on your preference – like Python, Ruby, C#, PHP and JavaScript (NodeJS). For the client-side, you'll mostly use JavaScript to access and communicate with the browser storage.</p>
<p>Alright, now let's learn about IndexedDB.</p>
<h2 id="heading-what-is-indexeddb">What is IndexedDB?</h2>
<p>Above we talked about non-relational databases and their different types. We also mentioned key-value databases as one of these types, right? Well, IndexedDB is an example of a key-value database.</p>
<h3 id="heading-what-is-a-key-value-database">What is a Key-Value Database?</h3>
<p>A key-value database means that all the data stored must be assigned to a key. It is one of the less complicated non-relational databases, at least in my opinion. </p>
<p>A key value database associates a key to a value. The key serves as a unique identifier for that value, which means that you can keep track of that value using the key.</p>
<p>If your app needs to fetch data constantly, key-value databases use really efficient and compact index structures to quickly and reliably locate values by their keys. Using the key you are able to not only retrieve the value stored, but also delete, update, and replace the value.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/key-value.png" alt="Image" width="600" height="400" loading="lazy">
<em><a target="_blank" href="https://mdn.github.io/learning-area/javascript/apis/client-side-storage/indexeddb/notes/">key-value database</a></em></p>
<p>Okay, I believe you understand what key-value database is all about now? let's continue talking about IndexedDB. </p>
<h3 id="heading-advantages-of-indexeddb"><strong>Advantages of IndexedDB</strong></h3>
<p>So we have all these browser storage options available to us, which is a great thing because we can choose one based on our needs. And each option has different capabilities. </p>
<p>So it's important to know how each works and their capabilities so you can choose the right one for your use case.</p>
<p>That being said, IndexedDB has the following advantages:</p>
<ol>
<li>IndexedDB is asynchronous, meaning it does not stop the user interface from rendering while the data loads.</li>
<li>It allows you to categorise your data using object stores.</li>
<li>It allows you to store large amounts of data.</li>
<li>It supports objects like videos, images, and so on – any object that supports a structured clone algorithm.</li>
<li>It supports database transactions and versioning.</li>
<li>It has great performance.</li>
<li>The database is private to an origin.</li>
<li>It is supported on all modern browsers.</li>
</ol>
<h3 id="heading-use-cases-of-indexeddb">Use Cases of IndexedDB</h3>
<p>Aside from knowing how IndexedDB works, it's also important to know when you should use it.</p>
<ul>
<li><strong>To store user-generated content:</strong> An example of user generated content is filling out an application form. While still in the process of completing the form, a user can leave it and come back some time later to complete the form without losing their initial data inputs.</li>
<li><strong>To store application state:</strong> When a user first loads a website or application, you can use IndexedDB to store these initial states. These can be log in authentications, API requests, or any other state needed before the UI is rendered. So when next the user visits the site, the load speed increases because the application has state already stored. This means that it renders the UI faster.</li>
<li><strong>For an application that works offline:</strong> Users can edit and add data while the application is offline. IndexedDB will process and empty these operations in a synchronization queue when the application comes online.</li>
</ul>
<h2 id="heading-how-indexeddb-works">How IndexedDB Works</h2>
<p>Now to the main part of this article: learning how IndexedDB works. We will be using the flowchart below, and we will go over the various events and paths one after the other and the associated JavaScript code to properly explain them.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/Untitled-Diagram-Page-1.drawio--1-.png" alt="Image" width="600" height="400" loading="lazy">
<em>IndexedDB event flowchart</em></p>
<h3 id="heading-path-1-what-to-do-if-the-database-does-not-exist">Path 1: What to do if the database does not exist</h3>
<p>When you create a new database in IndexedDB this is the path it will follow. This path is pretty straightforward:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/Untitled-Diagram-Page-2.drawio.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>An important thing to note is that, when creating a Database, you will have to give the database a name and a version (you determine any version to give the database). </p>
<p>Also, when you create a database for the first time, <strong>version 1</strong> is automatically assigned to it even without you stating a version.</p>
<p>Now, let's explain the flowchart above. When you create a database, it checks if a database with that name (dbname) exists already. </p>
<p>If it doesn't exist, it will proceed to call the <strong>upgrade</strong> event. When the upgrade event gets called, you can then upgrade the structure of the database. When the upgrade event block runs successfully, it will then call the <strong>success</strong> event.</p>
<pre><code>        <span class="hljs-keyword">const</span> request = indexedDB.open(<span class="hljs-string">'myDatabase'</span>, <span class="hljs-number">1</span>);

        <span class="hljs-comment">//upgrade event</span>
        request.onupgradeneeded = <span class="hljs-function">() =&gt;</span> {
            alert(<span class="hljs-string">"upgrade needed"</span>)
        }

        <span class="hljs-comment">//on success</span>
        request.onsuccess = <span class="hljs-function">() =&gt;</span> {
            alert(<span class="hljs-string">"success is called"</span>)
        }
</code></pre><h3 id="heading-path-2-what-to-do-if-the-database-exists-but-has-a-new-version-greater-than-the-previous-version">Path 2: What to do if the database exists but has a new version greater than the previous version</h3>
<p>Now we'll look at the second path. When a new database is created, it first checks to see if the database already exists. </p>
<p>If a database with the same name exists, it then checks the version to see if the version is greater than the previous version. If it is, it then calls the <strong>upgrade</strong> event where you can modify the structure of the database. And after that is done, it calls the <strong>success</strong> event.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/Untitled-Diagram-Page-3.drawio.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Following the explanation above, now let's look at the code below.</p>
<p>Let's assume we had already created a database with the name "myDatabase". Since the database name is the same as the one we previously created, it then moves to check the version. The previous version was "version 1". Since we changed the version to "version 2" and since version 2 &gt; version 1, it will then execute the modification inside the <strong>onupgradeneeded</strong> function.</p>
<pre><code>    <span class="hljs-keyword">const</span> request = indexedDB.open(<span class="hljs-string">'myDatabase'</span>, <span class="hljs-number">2</span>);

        <span class="hljs-comment">//upgrade event</span>
        request.onupgradeneeded = <span class="hljs-function">() =&gt;</span> {
            alert(<span class="hljs-string">"upgrade needed"</span>)
        }

        <span class="hljs-comment">//on success</span>
        request.onsuccess = <span class="hljs-function">() =&gt;</span> {
            alert(<span class="hljs-string">"success is called"</span>)
        }
</code></pre><h3 id="heading-path-3-what-to-do-if-the-database-exists-but-the-version-is-less-than-the-current-version">Path 3: What to do if the database exists, but the version is less than the current version</h3>
<p>Following the flowchart below, if the database already exists, and the version is less than the current version, it then moves to check if the version is the same as the current version. </p>
<p>There are two possible outcome here: first, if the version is the same as the current version it calls the <strong>success</strong> event, i.e. no update will be made, the database stays the same, no error is thrown. Second, if the version is less that the current version, it fails and throws an error.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/08/Untitled-Diagram-Page-4.drawio--3-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-how-to-create-an-object-store-and-transaction-in-indexeddb">How to create an Object Store and Transaction in IndexedDB</h3>
<ul>
<li><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore"><strong>Object Store</strong></a>: Is a collection of objects inside a database, a database can have different object stores. considering the code below, myDatabase is the database created, while myDatabaseStore is the object store created inside the database. The object store can be used to store any form of data. I used the code below to explain how to create an object store.</li>
</ul>
<pre><code><span class="hljs-keyword">let</span> db;

<span class="hljs-keyword">const</span> openRequest = indexedDB.open(<span class="hljs-string">'myDatabase'</span>, <span class="hljs-number">1</span>);

openRequest.onupgradeneeded = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">e</span>) </span>{
    db = e.target.result;
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'running onupgradeneeded'</span>);
    <span class="hljs-keyword">const</span> storeOS = db.createObjectStore(<span class="hljs-string">'myDatabaseStore'</span>,  {<span class="hljs-attr">keyPath</span>: <span class="hljs-string">"name"</span>});

 };
openRequest.onsuccess = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">e</span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'running onsuccess'</span>);
    db = e.target.result;
};
openRequest.onerror = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">e</span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'onerror! doesnt work'</span>);
};
</code></pre><p><img src="https://www.freecodecamp.org/news/content/images/2022/09/key-value-1.png" alt="Image" width="600" height="400" loading="lazy">
<em>Creating object store</em></p>
<ul>
<li><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/IDBTransaction"><strong>Transaction</strong></a>: A transaction is a sequence of task wrapper together. For a transaction to be successful, all the task wrapped into it must pass, if one fails, none will pass. If that happens, no update will be made to the database. Transaction has methods, properties and events you can explore. In the code below, I was able to add item to the object store by wrapping it in a transaction.</li>
</ul>
<pre><code><span class="hljs-keyword">let</span> db;

<span class="hljs-keyword">const</span> openRequest = indexedDB.open(<span class="hljs-string">'myDatabase'</span>, <span class="hljs-number">2</span>);

openRequest.onupgradeneeded = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">e</span>) </span>{
    db = e.target.result;
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'running onupgradeneeded'</span>);
    <span class="hljs-keyword">const</span> storeOS = db.createObjectStore(<span class="hljs-string">'myDatabaseStore'</span>,  {<span class="hljs-attr">keyPath</span>: <span class="hljs-string">"name"</span>});

};
openRequest.onsuccess = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">e</span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'running onsuccess'</span>);
    db = e.target.result;
    addItem();
};
openRequest.onerror = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">e</span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'onerror! doesnt work'</span>);
    <span class="hljs-built_in">console</span>.dir(e);
};

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">addItem</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">const</span> item = {
        <span class="hljs-attr">name</span>: <span class="hljs-string">'banana'</span>,
        <span class="hljs-attr">price</span>: <span class="hljs-string">'$2.99'</span>,
        <span class="hljs-attr">description</span>: <span class="hljs-string">'It is a purple banana!'</span>,
        <span class="hljs-attr">created</span>: <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>().getTime(),
    };
    <span class="hljs-keyword">const</span> tx = db.transaction(<span class="hljs-string">"myDatabaseStore"</span>, <span class="hljs-string">"readwrite"</span>);
    <span class="hljs-keyword">const</span> store = tx.objectStore(<span class="hljs-string">'myDatabaseStore'</span>);
    store.add(item);
}
</code></pre><p><img src="https://www.freecodecamp.org/news/content/images/2022/09/key-value-2.png" alt="Image" width="600" height="400" loading="lazy">
<em>Adding item to the store</em></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>IndexedDB is a very powerful client-side storage option that developers can use to provide a better user experience for their websites or applications. It helps you reduce the time it takes to load data from a website or application that your users visit frequently.</p>
<p>If you haven't built something with IndexedDB, I encourage you to try it out. This article did not cover how to do that, but there I materials online that will guide you. Building stuff will help you appreciate IndexeDB more.</p>
<p>I hope you enjoyed reading it as I enjoyed writing it.</p>
<p><strong>Relevant Documentation on IndexedDB:</strong></p>
<ul>
<li><a target="_blank" href="https://www.w3.org/TR/IndexedDB/#introduction">www.w3.org/IndexedDB</a></li>
<li><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API">developer.mozilla.org/IndexedDB</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
