<?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[ Ikegah Oliver - 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[ Ikegah Oliver - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Fri, 15 May 2026 22:29:21 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/author/Oliverkrane/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Run and Customize LLMs Locally with Ollama ]]>
                </title>
                <description>
                    <![CDATA[ In the long history of technological innovation, only a few developments have been as impactful as Large Language Models (LLMs). LLMs are advanced AI systems trained on vast datasets to understand, ge ]]>
                </description>
                <link>https://www.freecodecamp.org/news/run-and-customize-llms-locally-with-ollama/</link>
                <guid isPermaLink="false">69a6cd5c75d7a0f10015ca0d</guid>
                
                    <category>
                        <![CDATA[ LLM&#39;s  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ ollama ]]>
                    </category>
                
                    <category>
                        <![CDATA[ AI ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ikegah Oliver ]]>
                </dc:creator>
                <pubDate>Tue, 03 Mar 2026 12:00:28 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/uploads/covers/5fc16e412cae9c5b190b6cdd/1d477910-f378-421b-87a2-20e390738e7c.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In the long history of technological innovation, only a few developments have been as impactful as Large Language Models (LLMs). LLMs are advanced AI systems trained on vast datasets to understand, generate, and process human language for tasks like writing, translation, summarization, and powering chatbots.</p>
<p>Having a powerful tool like this available offline is a game-changer. These <strong>Local LLMs</strong> keep high-level intelligence at your fingertips, even when you're offline. By the end of this guide, you’ll understand what local LLMs are, why they matter, and how to run them yourself, both the easy way and the more technical way.</p>
<p>This guide is suited but not limited to:</p>
<ul>
<li><p>Developers, technical writers, or curious engineers.</p>
</li>
<li><p>Anyone comfortable with the terminal.</p>
</li>
<li><p>People with some exposure to AI tools (ChatGPT, Claude, and so on).</p>
</li>
<li><p>Anyone with little or no experience running LLMs locally.</p>
</li>
</ul>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a href="#heading-what-are-local-llms">What Are Local LLMs?</a></p>
</li>
<li><p><a href="#heading-what-running-locally-means">What Running “Locally” Means</a></p>
</li>
<li><p><a href="#heading-why-run-llms-locally">Why Run LLMs Locally?</a></p>
</li>
<li><p><a href="#heading-how-to-set-up-a-local-llm">How to Set Up a Local LLM</a></p>
</li>
<li><p><a href="#heading-what-is-ollama">What Is Ollama?</a></p>
</li>
<li><p><a href="#heading-how-ollama-operates">How Ollama Operates</a></p>
</li>
<li><p><a href="#heading-how-to-install-ollama">How to Install Ollama</a></p>
</li>
<li><p><a href="#heading-how-to-pull-an-llm">How to Pull an LLM</a></p>
</li>
<li><p><a href="#heading-how-to-run-your-llm">How to Run Your LLM</a></p>
</li>
<li><p><a href="#heading-how-to-customize-local-llms-in-ollama-with-modelfiles">How to Customize Local LLMs in Ollama with Modelfiles</a></p>
<ul>
<li><p><a href="#heading-what-are-modelfiles">What Are Modelfiles?</a></p>
</li>
<li><p><a href="#heading-how-to-customize-a-model">How to Customize a Model</a></p>
</li>
<li><p><a href="#heading-what-modelfiles-do-and-dont-do">What Modelfiles Do and Don't Do</a></p>
</li>
</ul>
</li>
<li><p><a href="#heading-conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-what-are-local-llms">What are Local LLMs?</h2>
<p>Local Large Language Models (LLMs) bring AI off the cloud and onto your personal hardware. While standard models are originally too large for consumer devices, a process called <strong>quantization</strong> reduces their numerical precision, much like compressing a large high-resolution video file so it can stream smoothly on a mobile phone. This allows powerful intelligence to run locally on your laptop without needing massive server farms.</p>
<p>Running models such as Meta’s Llama 3.3, Google’s Gemma 3, or Alibaba’s Qwen series locally ensures full data privacy and eliminates subscription costs. Because the AI lives on your machine, you get a fast, offline-capable workspace that keeps your code secure and under your direct control.</p>
<h2 id="heading-what-running-locally-means">What Running “Locally” Means</h2>
<p>To understand how local LLMs run on your machine, you have to look into the physical components of your computer. When you run a model like Llama 3 or Mistral locally, your hardware transforms from a general-purpose machine into a specialized AI engine.</p>
<p>The process relies on a tight coordination between four key hardware pillars: <strong>Storage, RAM, the GPU, and the CPU.</strong></p>
<h3 id="heading-storage-the-models-permanent-home">Storage (The model's permanent home)</h3>
<p>Before you can chat, you must download the model. Unlike a standard app, an LLM is primarily a massive file of "weights", numerical values that represent everything the AI knows.</p>
<ul>
<li><p><strong>The Files:</strong> You’ll likely see formats like .gguf or .safetensors. These files are large: a "small" 7B (7 billion parameter) model usually occupies <strong>5GB to 10GB</strong> of disk space.</p>
</li>
<li><p><strong>SSD vs. HDD:</strong> An SSD is mandatory. Because the computer must move several gigabytes of data into memory every time you launch the model, a traditional hard drive will leave you waiting minutes for the "brain" to wake up.</p>
</li>
</ul>
<h3 id="heading-vram-and-ram-the-models-workspace">VRAM and RAM (The Model’s Workspace)</h3>
<p>This is the most critical bottleneck. For an AI to respond quickly, its entire "brain" must fit into high-speed memory.</p>
<ul>
<li><p><strong>VRAM (Video RAM):</strong> This is the memory physically attached to your graphics card (GPU). It is significantly faster than regular system RAM. If your model fits entirely in VRAM, the AI will likely type faster than you can read.</p>
</li>
<li><p><strong>System RAM:</strong> If your model is too big for your GPU, the software will "spill over" into your computer’s regular RAM. While this allows you to run massive models on modest hardware, the speed penalty is severe—often dropping from 50 words per second to just one or two.</p>
</li>
</ul>
<h3 id="heading-the-gpu-the-mathematical-engine">The GPU (The Mathematical Engine)</h3>
<p>While your CPU is the "manager" of your computer, the <strong>GPU (Graphics Processing Unit)</strong> is the "mathematician."</p>
<ul>
<li><p><strong>Parallel Power:</strong> LLMs work by performing billions of simple math problems (matrix multiplications) at the same time. A CPU has a few powerful cores, but a GPU has thousands of smaller cores designed specifically for this parallel math.</p>
</li>
<li><p><strong>Unified Memory (Apple Silicon):</strong> On modern Macs (M1/M2/M3), the CPU and GPU share the same pool of memory. This "Unified Memory" is a game-changer for local AI, allowing even thin laptops to handle relatively large models that would typically require a chunky desktop GPU.</p>
</li>
</ul>
<p>For optimal performance, always compare your computer's specs with the model’s requirements to see which models you can comfortably run.</p>
<h2 id="heading-why-run-llms-locally">Why Run LLMs Locally?</h2>
<p>Running an LLM locally isn't just for tech enthusiasts, it’s a strategic move for anyone who wants full control over their AI. Core benefits of running an LLM locally are:</p>
<ol>
<li><p><strong>Offline Usage</strong>: You're not limited to the cloud. You can explore and use your data wherever you go. Whether you're on a plane or in a remote area, your AI works without an internet connection.</p>
</li>
<li><p><strong>Privacy and data ownership</strong>: Also, because you are not connected to the cloud, there is no risk of your data and prompts being exploited by a third party remotely or used to train a company’s next model.</p>
</li>
<li><p><strong>Cost control</strong>: No need for monthly subscriptions and API tokens. Once you have the hardware, running the model is essentially free, given its capabilities and your configurations.</p>
</li>
<li><p><strong>Customization &amp; Experimentation</strong>: If you have multiple models downloaded, you can "swap brains" instantly. Try different models, fine-tune them for specific tasks, and tweak settings that big providers keep locked.</p>
</li>
<li><p><strong>Faster iteration for dev workflows</strong>: For developers, local hosting eliminates network latency, allowing for near-instant responses and faster testing loops.</p>
</li>
</ol>
<h3 id="heading-tradeoffs">Tradeoffs</h3>
<p>Local LLMs have certain tradeoffs to consider:</p>
<ul>
<li><p><strong>Hardware Requirements:</strong> You’ll need a decent setup—specifically, a GPU with a good amount of VRAM (usually 8GB+) or a Mac with Apple Silicon (M1/M2/M3)—to achieve smooth performance.</p>
</li>
<li><p><strong>Performance Limitations:</strong> Local models are getting better every day, but they might not yet match the sheer "reasoning power" of a massive, billion-dollar cloud cluster like GPT-4.</p>
</li>
<li><p><strong>Initial Setup Friction:</strong> It isn’t always "plug and play." If you want to get hands-on with specific features, you will have to spend some time configuring software, downloading large model files, and troubleshooting your environment.</p>
</li>
</ul>
<p>Even with these trade-offs, having such a tool at your disposal and under your control remains a significant advantage in everyday life.</p>
<h2 id="heading-how-to-set-up-a-local-llm">How to Set Up a Local LLM</h2>
<p>There are many ways to get and set up a local LLM, but for this guide, you will use Ollama, a user-friendly tool that brings private, secure AI directly to your desktop. You will learn to pull and deploy high-performance models with a single command, optimize them for your specific CPU/GPU configuration, and use the powerful <strong>Modelfile</strong> system to "program" custom AI personalities tailored to your exact needs.</p>
<p>What We’ll Cover:</p>
<ul>
<li><p><strong>The Basics:</strong> Understanding how Ollama turns your PC into an AI powerhouse.</p>
</li>
<li><p><strong>Installation &amp; Setup:</strong> Getting up and running in under five minutes.</p>
</li>
<li><p><strong>Model Management:</strong> How to find, "pull" (download), and run models like Llama 3 or Mistral.</p>
</li>
<li><p><strong>Customization:</strong> Writing your first <strong>Modelfile</strong> to give your AI a specific job or personality.</p>
</li>
</ul>
<p>By the end of this, you will have a fully independent AI workstation, capable of sophisticated reasoning without ever sending a byte of data to the cloud.</p>
<h2 id="heading-what-is-ollama">What is Ollama?</h2>
<p><a href="https://ollama.com/">Ollama</a> is a free, open-source tool that makes running Large Language Models (LLMs) on your own hardware as easy as opening a web browser. It strips away the technical complexity that usually comes with AI research, giving you a clean, simple way to chat with, manage, and even customize your own AI models.</p>
<p>Before Ollama, running a local AI was a headache. You had to hunt for the right "weights" files on the internet, set up complex coding environments, and hope your hardware doesn't crash. Now, instead of spending hours configuring software, Ollama handles the heavy lifting. It automatically finds your graphics card (GPU) and tunes the settings for you.</p>
<h2 id="heading-how-ollama-operates">How Ollama Operates</h2>
<p>Ollama follows a simple "Mental Model" that mimics how you handle apps on a phone or music on a streaming service.</p>
<h3 id="heading-the-model-registry-the-library">The Model Registry (The Library)</h3>
<p>Ollama maintains a massive <a href="https://ollama.com/library">"Library"</a>, a central library of prepackaged AI models such as Llama 3, Mistral, and Gemma. You don't have to worry about file formats, you just pick a name from the list, and Ollama "pulls" it down to your machine.</p>
<h3 id="heading-the-local-runtime-the-engine">The Local Runtime (The Engine)</h3>
<p>Once you have a model, Ollama acts as the engine. It wakes the model up, loads it into your computer's memory (RAM/VRAM), and starts the mathematical "thinking" process. It is smart enough to use your GPU for speed, but it can also run on a standard CPU if that's all you have.</p>
<h3 id="heading-the-cli-the-control-centre">The CLI (The Control Centre)</h3>
<p>Ollama uses a <strong>Command Line Interface (CLI)</strong>. While that sounds technical, it just means you type simple, human-like instructions into a terminal window. Want to talk to a model? You just tell it to run. Want to see what you've downloaded? You ask it to list them.</p>
<h2 id="heading-how-to-install-ollama">How to Install Ollama</h2>
<p>Go to the Ollama <a href="https://ollama.com/download">download page</a>. For Windows and Mac, click the download button.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6349de767b9ff550634412bf/0e61c2b6-598f-49af-8de7-9029240ed9c2.png" alt="Screenshot of the Ollama download page showing macOS, Linux, and Windows options, with Windows selected and a PowerShell install command (irm https://ollama.com/install.ps1 | iex) plus a “Download for Windows” button (requires Windows 10 or later)." style="display:block;margin:0 auto" width="600" height="400" loading="lazy">

<p>For Linux, run this command:</p>
<pre><code class="language-plaintext">curl -fsSL https://ollama.com/install.sh | sh
</code></pre>
<p>After downloading, open the file, follow the setup instructions, and install it.</p>
<p>On Windows and Mac, after installation, the Ollama native Desktop Application should open.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6349de767b9ff550634412bf/811604e9-ad6a-44cb-afde-c842c249b32e.png" alt="Screenshot of the Ollama desktop app interface showing the sidebar with “New Chat” and “Settings,” a blank chat area with a llama icon, a message input field, and the selected model set to “llama2:7b.”" style="display:block;margin:0 auto" width="600" height="400" loading="lazy">

<p>This GUI is most beneficial for those who feel the CLI is intimidating; you don't have to be a coder to use Ollama. Instead of typing commands, you can manage your models and start conversations through a sleek window that feels just like any other chat app.</p>
<h2 id="heading-how-to-pull-an-llm">How to Pull an LLM</h2>
<p>As mentioned earlier, Ollama has a vast <a href="https://ollama.com/library">library</a> of Large Language Models for different specs and uses. To download one to your computer, use the pull command followed by the name of the LLM. For example:</p>
<pre><code class="language-plaintext">ollama pull gemma3:1b
</code></pre>
<p>To see the models you downloaded or have, use the list command, like:</p>
<pre><code class="language-plaintext">ollama list
</code></pre>
<h2 id="heading-how-to-run-your-llm">How to Run Your LLM</h2>
<p>You now have your LLM on your computer. To use it, you use the run command, followed by the name of the LLM. For example:</p>
<pre><code class="language-plaintext">ollama run gemma3:1b
</code></pre>
<p>The LLM will load up, and you can prompt it.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6349de767b9ff550634412bf/b78fba39-1de0-4ec8-b313-8bc19211bda9.png" alt="Screenshot of a Windows Command Prompt showing ollama run gemma3:1b executed successfully, with the prompt displaying “Send a message (/? for help)” indicating the model is ready for input." style="display:block;margin:0 auto" width="600" height="400" loading="lazy">

<p>To exit the LLM, use Ctrl + d or type in <code>/bye</code>.<br>You can perform other operations like deleting a model, copying a model, show information on a model, and so on. Type in ollama help to see all these commands.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6349de767b9ff550634412bf/a30f393e-0b88-40db-b5ef-e0e1e30acc43.png" alt="Screenshot of a command line interface on a dark background displays the help message for &quot;ollama&quot; with the title &quot;Large language model runner&quot;. It includes sections for &quot;Usage&quot; and &quot;Available Commands,&quot; listing options such as &quot;serve,&quot; &quot;create,&quot; &quot;show,&quot; &quot;run,&quot; &quot;stop,&quot; &quot;pull,&quot; and &quot;list,&quot; with brief descriptions of each. The bottom of the screen displays &quot;Flags,&quot; which lists options such as &quot;-h, --help,&quot; &quot;--verbose,&quot; and &quot;--version&quot;." style="display:block;margin:0 auto" width="600" height="400" loading="lazy">

<h2 id="heading-how-to-customize-local-llms-in-ollama-with-modelfiles">How to Customize Local LLMs in Ollama with Modelfiles</h2>
<p>One of Ollama’s most powerful features is the ability to customize how a local model behaves using <strong>Modelfiles</strong>. Rather than treating models as fixed black boxes, Modelfiles allow you to define <em>how</em> a model should respond, what role it should play, and how it should generate text, without retraining or fine-tuning.</p>
<p>This makes Modelfiles ideal for creating reusable, task-specific local models such as technical writers, code reviewers, research assistants, internal developer tools, or even character-driven assistants.</p>
<h2 id="heading-what-are-modelfiles">What are ModelFiles?</h2>
<p>A Modelfile is a plain-text configuration file used by Ollama to create a new model based on an existing one. It describes how a base model should be wrapped, prompted, and configured at runtime.</p>
<p>Essentially, a Modelfile:</p>
<ul>
<li><p>Starts from a base model</p>
</li>
<li><p>Applies a set of instructions</p>
</li>
<li><p>Produces a new, named model that can be run like any other</p>
</li>
</ul>
<p>Modelfiles do not modify the underlying model weights. Instead, they define behavioral rules, how the model should be prompted, how it should generate text, and how it should respond to user input.</p>
<h3 id="heading-modelfile-syntax-and-structure">Modelfile Syntax and Structure</h3>
<p>Modelfiles are line-based and declarative. Each directive defines a specific aspect of the model’s behavior.</p>
<p>A minimal Modelfile looks like this:</p>
<pre><code class="language-markdown">FROM llama3

SYSTEM """
You are a senior technical writer.
"""

PARAMETER temperature 0.2
</code></pre>
<ul>
<li><p><strong>FROM</strong>: This is the foundation. It tells the system which base architecture (like llama3) to inherit its intelligence and tokenizer from.</p>
</li>
<li><p><strong>SYSTEM</strong>: This sets the "permanent" instructions. By assigning the Senior Technical Writer role, we ensure that every response maintains a professional, structured tone without needing to remind the AI in every prompt.</p>
</li>
<li><p><strong>PARAMETER</strong>: These are the model's dials and knobs. In this case, we use the temperature 0.2 parameter to set a low "creativity dial," forcing the model to be more deterministic and precise, which is ideal for the consistent, factual output.</p>
</li>
</ul>
<p>Advanced users can also use TEMPLATE for custom prompt formatting and additional MESSAGE directives to include specific conversation history, though these aren't required for this basic setup.</p>
<p><strong>Quick reference cheat sheet:</strong></p>
<table style="min-width:75px"><colgroup><col style="min-width:25px"><col style="min-width:25px"><col style="min-width:25px"></colgroup><tbody><tr><td><p><strong>Directive</strong></p></td><td><p><strong>Purpose</strong></p></td><td><p><strong>Example</strong></p></td></tr><tr><td><p><strong>FROM</strong></p></td><td><p><strong>Required.</strong> Defines the base model.</p></td><td><p>FROM llama3</p></td></tr><tr><td><p><strong>SYSTEM</strong></p></td><td><p>Sets the model's persona and rules.</p></td><td><p>SYSTEM "You are a helpful assistant."</p></td></tr><tr><td><p><strong>PARAMETER</strong></p></td><td><p>Adjusts generation settings (randomness, context).</p></td><td><p>PARAMETER temperature 0.2</p></td></tr><tr><td><p><strong>TEMPLATE</strong></p></td><td><p>Formats how User/System prompts are structured.</p></td><td><p>TEMPLATE "{{ .System }}\nUser: {{ .Prompt }}"</p></td></tr><tr><td><p><strong>STOP</strong></p></td><td><p>Defines tokens that end the model's response.</p></td><td><p>STOP "&lt;/s&gt;"</p></td></tr><tr><td><p><strong>MESSAGE</strong></p></td><td><p>Adds specific message history to the model.</p></td><td><p>MESSAGE user "Hello!"</p></td></tr></tbody></table>

<h2 id="heading-how-to-customize-a-model">How to Customize a Model</h2>
<p>To create a model using a Modelfile, Ollama performs the following steps:</p>
<ul>
<li><p>Loads the specified base model</p>
</li>
<li><p>Applies system-level instructions</p>
</li>
<li><p>Configures generation parameters</p>
</li>
<li><p>Registers the result as a new local model</p>
</li>
</ul>
<p>For this article, you will be creating a technical writing assistant from any local LLM of your choice. You can use the LLM you downloaded earlier, or download another one you feel is a better fit for this model.</p>
<ol>
<li><p>Set up your environment: Create a folder named <code>my-writing-assistant</code>, then open it in your preferred IDE or text editor.</p>
</li>
<li><p>Create a Modelfile: Create a file named Modelfile in your folder. Populate it with the following:</p>
</li>
</ol>
<pre><code class="language-markdown">FROM llama3 

SYSTEM """
You are a senior technical writer.
Write clear, concise explanations.
Use headings and bullet points where appropriate.
Avoid marketing language.
"""

PARAMETER temperature 0.2
PARAMETER top_p 0.9
PARAMETER repeat_penalty 1.1
PARAMETER num_ctx 4096
</code></pre>
<ol>
<li><p>Create your model: Open the terminal in your IDE, or if you are using a text editor without a built-in terminal, open your Command Prompt and navigate into the my-writing-assistant directory. Run this command:</p>
<pre><code class="language-plaintext">ollama create tech-writer -f Modelfile
</code></pre>
<p>You should see a response like this:</p>
<img src="https://cdn.hashnode.com/uploads/covers/6349de767b9ff550634412bf/a403675f-396d-43af-b2ae-63bf3e56906c.png" alt="Screenshot of a command line interface showing the successful creation of a custom model named &quot;tech-writer&quot; using the command ollama create tech-writer -f Modelfile. The terminal displays progress logs for gathering components, using existing layers, and creating new layers, ending with a &quot;success&quot; message." style="display:block;margin:0 auto" width="600" height="400" loading="lazy">
</li>
<li><p>Run your model: You can run your model like any other Ollama model, with the run command:</p>
<pre><code class="language-plaintext">ollama run tech-writer
</code></pre>
<img src="https://cdn.hashnode.com/uploads/covers/6349de767b9ff550634412bf/ea8bb6a7-b64d-422c-9f52-6526ed1c8496.png" alt="Screenshot of a command line interface showing the command ollama run tech-writer being executed. Below the command, an interactive prompt appears with the text &quot;>>> Send a message (/? for help),&quot; indicating the custom model is ready for use." style="display:block;margin:0 auto" width="600" height="400" loading="lazy">

<p>Try a documentation-based prompt and see your model behave exactly how your Modelfile designed it.</p>
</li>
</ol>
<p>You can also interact with your models(downloaded and modified) using the <strong>Desktop App</strong>. Simply open the application, select your preferred model from the chatbox dropdown menu, and start prompting.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6349de767b9ff550634412bf/896cd707-0695-494c-b8a8-b70ded37ce10.png" alt="A screenshot of a white theme chat interface showing a model selection dropdown menu open." style="display:block;margin:0 auto" width="600" height="400" loading="lazy">

<h2 id="heading-what-modelfiles-do-and-dont-do">What Modelfiles Do and Don't Do</h2>
<p>Modelfiles are powerful, but it’s important to understand their scope.</p>
<p>They:</p>
<ul>
<li><p>Customize model behavior</p>
</li>
<li><p>Enforce consistent prompting</p>
</li>
<li><p>Tune generation characteristics</p>
</li>
<li><p>Create reusable local models</p>
</li>
</ul>
<p>They do not:</p>
<ul>
<li><p>Retrain or fine-tune model weights</p>
</li>
<li><p>Add new knowledge</p>
</li>
<li><p>Change the model’s architecture</p>
</li>
</ul>
<p>A Modelfile shapes how a model responds, not what it knows.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Running large language models locally is no longer limited to researchers or high-end machines. With Ollama and Modelfiles, you can download capable models, run them on your own device, and tailor their behavior to fit your workflow.</p>
<p>In this guide, we covered what local LLMs are, why they matter, how Ollama simplifies setup, and how Modelfiles let you control tone, structure, and generation settings. Instead of relying on a generic chatbot, you can build assistants that feel intentional and purpose-built.</p>
<p>More importantly, running models locally changes how you interact with AI. You move from simply consuming an API to understanding and shaping the system itself. As AI continues to influence software, business, and everyday tools, hands-on experience with local models gives you a clearer view of where the technology is heading. The best way to understand that shift is to experiment, pull a model, refine a Modelfile,</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Publish an npm Package - Explained with Examples ]]>
                </title>
                <description>
                    <![CDATA[ If you’ve spent any time working with JavaScript, you’ve most likely come across npm—whether installing packages like Express, Lodash, or React, or running commands like npm init. While using npm is second nature for many JavaScript developers, some ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-publish-an-npm-package/</link>
                <guid isPermaLink="false">68d44cc07b532bf921e47213</guid>
                
                    <category>
                        <![CDATA[ npm ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ open source ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ikegah Oliver ]]>
                </dc:creator>
                <pubDate>Wed, 24 Sep 2025 19:55:44 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1758743190885/78dd4f19-53eb-4101-9cf9-7c22ab5f6be2.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you’ve spent any time working with JavaScript, you’ve most likely come across npm—whether installing packages like Express, Lodash, or React, or running commands like <code>npm init</code>. While using npm is second nature for many JavaScript developers, some have never explored how those packages are created, structured, and shared with the rest of the world. Behind each command lies a powerful system for building, managing, and distributing JavaScript code at scale.</p>
<p>This article will guide you through the basics of npm, explain how it functions behind the scenes, and demonstrate step-by-step how to create and publish your own npm package to the official npm registry.  Whether you’re a beginner just starting with JavaScript or a seasoned developer who has used npm but never published a package, this guide will help you confidently navigate the entire process, from setup to sharing your code with the global developer community.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-is-npm">What is npm?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-components-of-npm">Components of npm</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-command-line-interface">The Command Line Interface</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-registry">The Registry</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-website">The Website</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-is-the-packagejson-file">What is the Package.json File?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-npm-works">How npm Works</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-publish-an-npm-library">How to Publish an npm Library</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-verify-and-install-your-package">How to Verify and Install Your Package</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-update-your-package">How to Update Your Package</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-notes-and-best-practices">Notes and Best Practices</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-beyond-the-basics">Beyond the Basics</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-what-is-npm">What is npm?</h2>
<p>npm, which stands for Node Package Manager, is a command-line tool for installing and managing JavaScript packages. It is an ecosystem that powers modern JavaScript development (<a target="_blank" href="http://node.js">Node.js</a>, frontend tools, frameworks, and so on). Developers use npm to share and borrow packages, and many organizations use npm to manage private development.</p>
<p>Essentially, npm is to JavaScript what pip is to Python or Maven to Java. It enables developers to reuse code written by others (most of the time to fulfil a function in their project), manage dependencies, and share their own code with the world.</p>
<p>You can use npm to:</p>
<ul>
<li><p>Get and utilize code packages in your applications, either as-is or with custom modifications.</p>
</li>
<li><p>Download and run standalone tools instantly.</p>
</li>
<li><p>Execute packages directly from the registry without installing them using npx.</p>
</li>
<li><p>Share your own code with developers around the world through the npm registry.</p>
</li>
<li><p>Limit access to specific packages so only approved developers can use them.</p>
</li>
<li><p>Create organizations to manage code, teams, and packages in one place.</p>
</li>
<li><p>Collaborate as virtual teams using shared organizational accounts.</p>
</li>
<li><p>Handle different versions of packages and their dependencies with ease.</p>
</li>
<li><p>Keep your applications up to date by syncing with the latest package updates.</p>
</li>
<li><p>Explore different packages that offer various solutions to the same problem.</p>
</li>
<li><p>Connect with developers working on similar challenges and projects.</p>
</li>
</ul>
<h2 id="heading-components-of-npm">Components of npm</h2>
<p>npm consists of three core components:</p>
<ul>
<li><p>The command line interface (CLI)</p>
</li>
<li><p>The registry</p>
</li>
<li><p>The website</p>
</li>
</ul>
<h2 id="heading-the-command-line-interface">The Command Line Interface</h2>
<p>There are different npm commands you can run on your terminal. For example, <code>npm init</code> can be used to initialize a Node project, <code>npm install</code> can be used to install a package. It also allows you to do things like:</p>
<ul>
<li><p>Publish packages (<code>npm publish</code>)</p>
</li>
<li><p>Update packages (<code>npm update</code>)</p>
</li>
<li><p>Manage versioning (<code>npm version</code>)</p>
</li>
<li><p>Run scripts (<code>npm run build</code>, <code>npm test</code>, and so on)</p>
</li>
</ul>
<p>Think of it as your control panel.</p>
<h2 id="heading-the-registry">The Registry</h2>
<p>You can find the huge public database at <a target="_blank" href="https://registry.npmjs.org">https://registry.npmjs.org</a>, where packages are stored and shared. It also contains all the meta-information surrounding the package.</p>
<p>Example, when you run:</p>
<pre><code class="lang-bash">npm install express
</code></pre>
<p>npm fetches the Express package from the registry.</p>
<p>The npm registry enables collaboration by allowing developers to:</p>
<ul>
<li><p>Publish their own packages</p>
</li>
<li><p>Install packages created by others</p>
</li>
<li><p>Discover new tools and libraries</p>
</li>
</ul>
<p>Its collaboration features include:</p>
<ul>
<li><p>Open-source packages: The code is publicly visible (usually hosted on GitHub).</p>
</li>
<li><p>Versioning: Multiple versions of the same package let users safely adopt updates.</p>
</li>
<li><p>Scoped packages: Namespaces allow teams and organizations to manage ownership.</p>
</li>
<li><p>Issues &amp; pull requests: Most npm packages link to GitHub, allowing developers too contribute fixes and enhancements.</p>
</li>
<li><p>Organisations: Teams can manage access to shared private or public packages.</p>
</li>
</ul>
<h2 id="heading-the-website">The Website</h2>
<p>At <a target="_blank" href="https://www.npmjs.com">https://www.npmjs.com</a>, this is where you can:</p>
<ul>
<li><p>Browse packages.</p>
</li>
<li><p>Read documentation.</p>
</li>
<li><p>View download stats and dependencies.</p>
</li>
<li><p>Create and manage your account, organization, and package access.</p>
</li>
</ul>
<h2 id="heading-what-is-the-packagejson-file">What is the Package.json File?</h2>
<p>A very important component of any npm tool that you’ll come across as a JavaScript developer installing an npm package, is the <code>package.json</code> file. It is a metadata file that lives at the root of every npm or Node project. It tells npm (and other tools) everything it needs to know about your project, like:</p>
<ul>
<li><p>What the project is called.</p>
</li>
<li><p>What it depends on</p>
</li>
<li><p>How to run it</p>
</li>
<li><p>How to version it</p>
</li>
<li><p>and how to publish it</p>
</li>
</ul>
<p>You can think of it like the blueprint of your JavaScript project. Without it, npm doesn't know how to work with your code.</p>
<p>You can create a <code>package.json</code> file by typing the command <code>npm init</code> in your terminal and filling in the prompts provided. Alternatively, you can create a file named <code>package.json</code> and manually populate it with JSON content.</p>
<h3 id="heading-key-fields-in-an-npm-packagejson-file">Key Fields in an npm package.json File</h3>
<p>The following is a list of commonly used fields and how they interact with npm:</p>
<ol>
<li><p><code>name</code> and <code>version</code></p>
<pre><code class="lang-json"> <span class="hljs-string">"name"</span>: <span class="hljs-string">"my-awesome-package"</span>,
 <span class="hljs-string">"version"</span>: <span class="hljs-string">"1.0.0"</span>
</code></pre>
<ul>
<li><p>This is required for publishing.</p>
</li>
<li><p><code>name</code> must be unique (if publishing to the public npm registry).</p>
</li>
<li><p><code>version</code> follows semantic versioning (semver) (for example, major.minor.patch).  </p>
</li>
</ul>
</li>
<li><p><code>description</code>, <code>keywords</code>, <code>author</code>, and <code>license</code></p>
<pre><code class="lang-json"> <span class="hljs-string">"description"</span>: <span class="hljs-string">"A utility to convert markdown to HTML"</span>,
 <span class="hljs-string">"keywords"</span>: [<span class="hljs-string">"markdown"</span>, <span class="hljs-string">"html"</span>, <span class="hljs-string">"converter"</span>],
 <span class="hljs-string">"author"</span>: <span class="hljs-string">"Ikegah Oliver"</span>,
 <span class="hljs-string">"license"</span>: <span class="hljs-string">"MIT"</span>
</code></pre>
<ul>
<li><p>Helps npm users discover your package</p>
</li>
<li><p>Show up on <a target="_blank" href="http://npmjs.com">npmjs.com</a>.</p>
</li>
<li><p>Sets collaboratory license</p>
</li>
</ul>
</li>
<li><p><code>scripts</code></p>
<pre><code class="lang-json"> <span class="hljs-string">"scripts"</span>: {
   <span class="hljs-attr">"start"</span>: <span class="hljs-string">"node index.js"</span>,
   <span class="hljs-attr">"test"</span>: <span class="hljs-string">"jest"</span>,
   <span class="hljs-attr">"build"</span>: <span class="hljs-string">"tsc"</span>
 }
</code></pre>
<ul>
<li><p>Defines custom commands.</p>
</li>
<li><p>Run with npm run test, npm run build, and so on.</p>
</li>
<li><p>Automates build, test, lint, deploy processes.</p>
</li>
</ul>
</li>
<li><p><code>main</code> and <code>exports</code></p>
<pre><code class="lang-json"> <span class="hljs-string">"main"</span>: <span class="hljs-string">"dist/index.js"</span>,
 <span class="hljs-string">"exports"</span>: {
   <span class="hljs-attr">"."</span>: <span class="hljs-string">"./dist/index.js"</span>
 }
</code></pre>
<ul>
<li><p><code>main</code>: Entry point for <code>require()</code> or import.</p>
</li>
<li><p><code>exports</code>: Controls exactly what parts of your package are exposed (especially useful for modern ESM and package security).</p>
</li>
</ul>
</li>
<li><p><code>dependencies</code> and <code>devDependencies</code></p>
<pre><code class="lang-json"> <span class="hljs-string">"dependencies"</span>: {
   <span class="hljs-attr">"express"</span>: <span class="hljs-string">"^4.18.2"</span>
 },
 <span class="hljs-string">"devDependencies"</span>: {
   <span class="hljs-attr">"eslint"</span>: <span class="hljs-string">"^8.0.0"</span>,
   <span class="hljs-attr">"jest"</span>: <span class="hljs-string">"^29.0.0"</span>
 }
</code></pre>
<ul>
<li><p><code>dependencies</code> : Core packages your project needs to run in production (for example, <code>express</code>).</p>
</li>
<li><p><code>devDependencies</code> : Packages used only during development, like testing or build tools (for example, <code>jest</code>).</p>
</li>
</ul>
</li>
<li><p><code>engines</code></p>
<pre><code class="lang-json"> <span class="hljs-string">"engines"</span>: {
   <span class="hljs-attr">"node"</span>: <span class="hljs-string">"&gt;=14.0.0"</span>
 }
</code></pre>
<ul>
<li><p>Specifies Node.js version your package supports.</p>
</li>
<li><p>Helps warn users before they install with an unsupported version.</p>
</li>
</ul>
</li>
<li><p><code>private</code></p>
<pre><code class="lang-json"> <span class="hljs-string">"private"</span>:<span class="hljs-string">"true"</span>
</code></pre>
<ul>
<li><p>Prevents accidental publishing to the public npm registry.</p>
</li>
<li><p>Used for monorepos and internal-only projects.</p>
</li>
</ul>
</li>
<li><p><code>files</code> (optional)</p>
<pre><code class="lang-json"> <span class="hljs-string">"files"</span>:[<span class="hljs-string">"/dist"</span>, <span class="hljs-string">"README.md"</span>]
</code></pre>
<ul>
<li><p>Controls what files get included when you run npm publish.</p>
</li>
<li><p>Reduces package size, omits build artifacts or test files.</p>
</li>
</ul>
</li>
</ol>
<p>A minimal npm <code>package.json</code> file looks like this:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"name"</span>: <span class="hljs-string">"@oliver/markdown-to-html"</span>,
  <span class="hljs-attr">"version"</span>: <span class="hljs-string">"1.0.0"</span>,
  <span class="hljs-attr">"description"</span>: <span class="hljs-string">"Converts markdown to HTML with styles"</span>,
  <span class="hljs-attr">"main"</span>: <span class="hljs-string">"dist/index.js"</span>,
  <span class="hljs-attr">"scripts"</span>: {
    <span class="hljs-attr">"build"</span>: <span class="hljs-string">"tsc"</span>,
    <span class="hljs-attr">"test"</span>: <span class="hljs-string">"jest"</span>
  },
  <span class="hljs-attr">"keywords"</span>: [<span class="hljs-string">"markdown"</span>, <span class="hljs-string">"html"</span>, <span class="hljs-string">"converter"</span>],
  <span class="hljs-attr">"author"</span>: <span class="hljs-string">"Ikegah Oliver"</span>,
  <span class="hljs-attr">"license"</span>: <span class="hljs-string">"MIT"</span>,
  <span class="hljs-attr">"dependencies"</span>: {
    <span class="hljs-attr">"marked"</span>: <span class="hljs-string">"^5.0.0"</span>
  },
  <span class="hljs-attr">"devDependencies"</span>: {
    <span class="hljs-attr">"jest"</span>: <span class="hljs-string">"^29.0.0"</span>
  },
  <span class="hljs-attr">"engines"</span>: {
    <span class="hljs-attr">"node"</span>: <span class="hljs-string">"&gt;=14.0.0"</span>
  },
  <span class="hljs-attr">"files"</span>: [<span class="hljs-string">"dist/"</span>, <span class="hljs-string">"README.md"</span>]
}
</code></pre>
<p>The <code>package.json</code> file plays a central role in every npm workflow. It defines your project's identity, lists its dependencies, specifies useful scripts, and outlines how the package should behave when published. Without it, npm can't properly install packages, run commands, or publish your code to the registry.</p>
<h2 id="heading-how-npm-works">How npm Works</h2>
<p>When you type <code>npm install</code> in your terminal, npm initiates a behind-the-scenes process to install the necessary packages for your project. Depending on how you run the command, the process varies slightly as follows:</p>
<h3 id="heading-method-1-packagejson-already-has-dependencies"><strong>Method 1</strong> - <code>package.json</code> Already Has Dependencies</h3>
<p>If your <code>package.json</code> lists packages under <code>dependencies</code> or <code>devDependencies</code>, npm will:</p>
<ol>
<li><p><strong>Read those entries:</strong> It looks at the names and version ranges of each dependency.</p>
</li>
<li><p><strong>Contact the registry:</strong> npm queries <a target="_blank" href="https://registry.npmjs.org">https://registry.npmjs.org</a> to fetch metadata about each required package.</p>
</li>
<li><p><strong>Download the correct versions:</strong> It selects versions that match your version rules (such as ^4.17.0) and downloads the <code>.tgz</code> files.</p>
</li>
<li><p><strong>Unpack and install:</strong> It places the packages into the <code>node_modules</code> directory and caches them.</p>
</li>
<li><p><strong>Update package-lock.json:</strong> It logs the exact versions and dependency tree in this file to ensure consistent installs later.</p>
</li>
</ol>
<h3 id="heading-method-2-you-run-npm-install-without-existing-dependencies"><strong>Method 2</strong> - You Run <code>npm install &lt;package-name&gt;</code> Without Existing Dependencies</h3>
<p>If your <code>package.json</code> doesn't have any dependencies yet and you run something like this in your terminal:</p>
<pre><code class="lang-bash">npm install express
</code></pre>
<p>Then npm will run:</p>
<ol>
<li><p><strong>Resolve the package version:</strong> It fetches the latest version of Express (unless you specify a version manually).</p>
</li>
<li><p><strong>Download and install:</strong> The tarball is downloaded and placed in the <code>node_modules/</code> folder that is automatically generated. A tarball is the zipped-up version of the package (<code>express</code> in this case), containing the package’s JavaScript files, a <code>package.json</code>, a README, and anything else the author included for distribution that npm downloads and extracts onto your machine.</p>
</li>
<li><p><strong>Add to</strong> <code>package.json</code>: npm automatically adds the package to your dependencies list like this:</p>
</li>
</ol>
<pre><code class="lang-json"><span class="hljs-string">"dependencies"</span>: {
  <span class="hljs-attr">"express"</span>: <span class="hljs-string">"^4.18.2"</span>
}
</code></pre>
<ol start="4">
<li><strong>Create a</strong> <code>package-lock.json</code> <strong>(if it doesn't exist):</strong> It writes all the version info to lock things down for future installs.</li>
</ol>
<p>Note: If you run <code>npm install --save-dev jest</code>It’ll add the package under devDependencies instead.</p>
<h2 id="heading-how-to-publish-an-npm-library">How to Publish an npm Library</h2>
<p>To follow through with this guide section, you will need to have the following prerequisites:</p>
<ul>
<li><p>Stable network connection</p>
</li>
<li><p>A code editor with a terminal (like VSCode)</p>
</li>
<li><p>Basic knowledge of JavaScript and Node</p>
</li>
<li><p>A basic understanding of the Markdown Markup language (for README documentation)</p>
</li>
</ul>
<p>Now, let’s dive into publishing an npm library. Assuming you just built and tested a fantastic JavaScript tool that you would like to share with the world, and allow people to use it in their projects and applications, the steps below will guide you from having the tool on your local machine to making it publicly available as an npm package for anyone to install and enjoy:</p>
<h3 id="heading-step-1-create-a-free-npm-account">Step 1: Create a free npm account</h3>
<p>Before publishing, you will need an npm account.</p>
<ul>
<li><p>Go to <a target="_blank" href="https://www.npmjs.com/signup">https://www.npmjs.com/signup</a>.</p>
</li>
<li><p>Fill in the form with your username, email, and password.</p>
</li>
<li><p>Confirm your email address by clicking the link in the verification email.</p>
</li>
</ul>
<h3 id="heading-step-2-log-in-from-the-command-line">Step 2: Log in from the Command Line</h3>
<p>Once you’ve created your account, you need to log in through your terminal. Run:</p>
<pre><code class="lang-bash">npm login
</code></pre>
<p>npm will prompt you for your username, password, and email address. If everything is correct, npm will generate an authentication token and store it locally, so you don’t have to log in every time.</p>
<h3 id="heading-step-3-create-a-packagejson-file">Step 3: Create a <code>package.json</code> file</h3>
<p>If your project doesn't already have a <code>package.json</code> file, create one by typing this command in your terminal:</p>
<pre><code class="lang-bash">npm init
</code></pre>
<p>You will be prompted to fill in the following information:</p>
<ul>
<li><p><strong>name</strong>: Must be unique if it’s public.</p>
</li>
<li><p><strong>version</strong>: Start with 1.0.0 (it represents the first version of your project; subsequently, you will change it accordingly after each update push) </p>
</li>
<li><p><strong>description</strong>: One-line summary of your package.</p>
</li>
<li><p><strong>entry point</strong>: Entry file of your project, usually <code>index.js</code> or <code>dist/index.js</code>.</p>
</li>
<li><p><strong>keywords</strong>: Help others discover your package.</p>
</li>
<li><p><strong>author</strong>: Your name or GitHub handle.</p>
</li>
<li><p><strong>license</strong>: Use MIT, ISC, or another open-source license.</p>
</li>
</ul>
<p>When you’re done, npm will generate a <code>package.json</code> like this:</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"name"</span>: <span class="hljs-string">"my-awesome-package"</span>,
  <span class="hljs-attr">"version"</span>: <span class="hljs-string">"1.0.0"</span>,
  <span class="hljs-attr">"description"</span>: <span class="hljs-string">"A demo package for npm publishing"</span>,
  <span class="hljs-attr">"main"</span>: <span class="hljs-string">"index.js"</span>,
  <span class="hljs-attr">"keywords"</span>: [<span class="hljs-string">"demo"</span>, <span class="hljs-string">"npm"</span>, <span class="hljs-string">"tutorial"</span>],
  <span class="hljs-attr">"author"</span>: <span class="hljs-string">"Your Name"</span>,
  <span class="hljs-attr">"license"</span>: <span class="hljs-string">"MIT"</span>
}
</code></pre>
<h3 id="heading-step-4-add-a-readmemdhttpreadmemd">Step 4: Add a <a target="_blank" href="http://readme.md">README.md</a></h3>
<p>Explain what your package does and how to use it in a <code>README.md</code> file. The README appears on your package page on <a target="_blank" href="http://npmjs.com">npmjs.com</a>. Example content:</p>
<pre><code class="lang-markdown"><span class="hljs-section"># my-awesome-package</span>

A simple package that says hello.

<span class="hljs-section">## Usage</span>

<span class="hljs-code">```js
const greet = require('my-awesome-package');
console.log(greet('Oliver'));
// Output: Hello, Oliver!</span>
</code></pre>
<h3 id="heading-step-5add-an-npmignore-file">Step 5:Add an .npmignore file</h3>
<p>This will exclude folders like <code>node_modules</code>, <code>dist</code>, or <code>.env</code>, and any other file or folder within the package you don’t wish to publish. Example content:</p>
<pre><code class="lang-bash">node_modules
.env
dist
</code></pre>
<h3 id="heading-step-6-check-if-the-package-name-you-chose-is-available">Step 6: Check if the package name you chose is available</h3>
<p>Before publishing, check if the package name you chose is not already taken. To check, run this command on your terminal:</p>
<pre><code class="lang-bash">npm search my-awesome-package
</code></pre>
<p>Or enter the URL <a target="_blank" href="https://www.npmjs.com/package/my-awesome-package">https://www.npmjs.com/package/my-awesome-package</a> in your browser (replace my-awesome-package with the name you chose). If no package page shows up, the name is not taken.</p>
<p>If the package name has been taken, change it in your <code>package.json</code> and any documentation (<code>README.md</code>), the name is reflected, or publish it under a scope. A scope is like a namespace tied to your npm username or organization. It ensures your package name is unique, even if the base name is common. For example, if my-awesome-package is taken, you can publish under a scope by setting the name section in its <code>package.json</code> like this: </p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"name"</span>: <span class="hljs-string">"@yourname/my-awesome-package"</span>
}
</code></pre>
<h3 id="heading-step-6-publish-your-package">Step 6: Publish your package</h3>
<p>You are now ready to publish. Run:</p>
<pre><code class="lang-bash">npm publish
</code></pre>
<p>If you used a scoped name, when publishing, you must make it public:</p>
<pre><code class="lang-bash">npm publish --access public
</code></pre>
<p>If everything is valid, npm will publish your package and give you a URL like:</p>
<p><a target="_blank" href="https://www.npmjs.com/package/my-awesome-package">https://www.npmjs.com/package/my-awesome-package</a></p>
<h2 id="heading-how-to-verify-and-install-your-package">How to Verify and Install Your Package</h2>
<p>Visit your project page on npm to see it live. For example: <a target="_blank" href="https://www.npmjs.com/package/my-awesome-package">https://www.npmjs.com/package/my-awesome-package</a>, or search your project name on the npm website search bar.</p>
<p>Now, try installing it in a node project:</p>
<pre><code class="lang-bash">npm install my-awesome-package
</code></pre>
<p>Test out its features and functionalities, depending on what it is built to do.</p>
<h2 id="heading-how-to-update-your-package">How to Update Your Package</h2>
<p>If you make changes or update features in your package, you can publish the update.</p>
<p>After applying your changes, you can update the version in your <code>package.json</code>. Using semantic versioning, you can update it as follows:</p>
<ul>
<li><p>Patch update: 1.0.0 → 1.0.1</p>
</li>
<li><p>Minor update: 1.0.0 → 1.1.0</p>
</li>
<li><p>Major update: 1.0.0 → 2.0.0</p>
</li>
</ul>
<p>Or you can use the CLI:</p>
<pre><code class="lang-bash">npm version &lt;update_type&gt;
</code></pre>
<p>Replace <code>&lt;update_type&gt;</code> with your new semantic version. </p>
<p>Now run:</p>
<pre><code class="lang-bash">npm publish
</code></pre>
<h2 id="heading-notes-and-best-practices">Notes and Best Practices</h2>
<p>Although publishing to npm is straightforward, you still need to follow best practices to maintain a clean, secure, and user-friendly package.</p>
<ul>
<li><p>Exclude Sensitive Files: Never include <code>.env</code>, credentials, or secrets. Use <code>.npmignore</code> or the "files" field in <code>package.json</code> to control what gets published.</p>
</li>
<li><p>Test Before Publishing: Run <code>npm pack</code> to preview the package and install it locally in another project to ensure everything works.</p>
</li>
<li><p>Unpublish Carefully: You can unpublish within 72 hours using <code>npm unpublish --force</code>, but avoid doing this frequently to prevent breaking other projects that rely on your package.</p>
</li>
<li><p>Always Bump the Version: npm won’t let you overwrite a version, so use semantic versioning (npm version patch|minor|major) before publishing updates.</p>
</li>
<li><p>Add Essentials: Include a clear <code>README.md</code> file, a license, and relevant keywords to make your package discoverable and easy to use.</p>
</li>
</ul>
<h2 id="heading-beyond-the-basics">Beyond the Basics</h2>
<p>Now that you've got the hang of the basics, you can put your npm skills to work and level up as a developer. Here are some simple, practical steps you can take:</p>
<h3 id="heading-get-involved-in-open-source">Get Involved in Open Source</h3>
<p>One of the best ways to gain real-world experience is by contributing to existing projects on npm. Check out their repositories on GitHub and GitLab and see how you can contribute to them. This teaches you how to collaborate, handle code reviews, and manage versions. A great way to start is by looking for projects on GitHub with a "good first issue" label.</p>
<h3 id="heading-maintain-your-own-package">Maintain Your Own Package</h3>
<p>Publishing is just the first step. To truly master the process, keep your package up to date. This involves fixing bugs, listening to user feedback, and adding new features. You will quickly learn about versioning, ensuring your package remains compatible with older projects, and effectively manage dependencies.</p>
<h3 id="heading-dig-into-advanced-features">Dig into Advanced Features</h3>
<p>Explore advanced npm topics like semantic versioning, using private packages, creating scoped packages, and automating your releases with CI/CD pipelines. These are essential skills for any professional developer.</p>
<p>Taking these steps will help you transition from merely understanding npm to confidently utilizing it in real-world scenarios.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Congratulations! You have now learned the essentials of npm from the <code>package.json</code> file to publishing and maintaining a JavaScript package with the npm library. With this knowledge, you can share your JavaScript tools with the world, collaborate with other developers, and contribute to the growing ecosystem of open-source libraries.</p>
<p>By following best practices, testing locally, and learning from standard errors, you can confidently create packages that are clean, secure, and useful for other developers. Whether you’re building a small utility or a full-fledged framework, publishing on npm gives your ideas visibility and helps you contribute to the wider JavaScript community.</p>
<p>If you’d like to get hands-on experience collaborating on a real package, I published an npm project called <a target="_blank" href="https://www.npmjs.com/package/route-pilot?activeTab=readme">route-pilot</a>, a powerful CLI tool for testing and analyzing Express.js routes in your Node.js applications. I’m actively seeking contributors who want to enhance the code, add new features, or refine the documentation. It’s a simple way to practice working with npm in a collaborative setting while learning more about open-source development. Head over to the <a target="_blank" href="https://github.com/oliverTwist2/express-route-tester">GitHub repo</a> and join in. We’d love to have you on board!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Learn REST API Principles by Building an Express App ]]>
                </title>
                <description>
                    <![CDATA[ Web development revolves around communication – communication between browsers and servers, as well as frontend applications and backends. At the centre of this is the API. And the REST architecture has become a popular way to design APIs that are cl... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/learn-rest-api-principles-by-building-an-express-app/</link>
                <guid isPermaLink="false">68066255e4a48bef99b3c63e</guid>
                
                    <category>
                        <![CDATA[ REST API ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Express ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ikegah Oliver ]]>
                </dc:creator>
                <pubDate>Mon, 21 Apr 2025 15:20:53 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1745003938509/442fd99e-d098-4a5a-98d7-94c4af9a5d55.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Web development revolves around communication – communication between browsers and servers, as well as frontend applications and backends. At the centre of this is the API. And the REST architecture has become a popular way to design APIs that are clean, consistent, and easy to use in web development.</p>
<p>REST works so well because it speaks the web’s native language. It uses familiar HTTP methods like <code>GET</code>, <code>POST</code>, <code>PUT</code>, and <code>DELETE</code>, treats data as resources, and follows clear conventions. All this makes it easy to understand, quick to implement, and widely supported, which is why most modern web APIs follow REST principles.</p>
<p>In this article, I will explore REST concepts and core principles while we build a simple Express application step by step. You will learn:</p>
<ul>
<li><p>What is REST architecture, and what are its advantages in web development?</p>
</li>
<li><p>The core REST principles (statelessness, resources, HTTP methods, and so on)</p>
</li>
<li><p>How to implement these principles in a real Express.js app</p>
</li>
<li><p>Best practices for designing clean and consistent APIs</p>
</li>
</ul>
<h3 id="heading-heres-what-we-will-cover">Here’s what we will cover:</h3>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-is-rest">What is REST</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-why-use-rest">Why use REST?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-core-principles-of-rest-architecture">Core Principles of REST Architecture</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-build-a-simple-express-app">Build a Simple Express App</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-is-express">What is Express?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-set-up-the-express-app">Set Up the Express App</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-build-restful-resources">Build RESTful Resources</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-middlewares">Middlewares</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-test-your-express-app">Test your Express App</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-bad-rest-practices-to-avoid">Bad REST Practices to Avoid</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-what-is-rest">What is REST?</h2>
<p>Representational State Transfer (REST) is a style of designing networked applications that emphasises a stateless client-server communication model centred around resources. Think of it like ordering at a restaurant: each time you ask for something, you have to tell the waiter exactly what you want, and they don't remember your previous orders.</p>
<p>RESTful APIs treat data as resources, each accessible through a unique web address (URI). Then, it leverages the standard actions defined by HTTP methods – POST to create new resources, GET to retrieve them, PUT to modify existing ones, and DELETE to remove them – providing a consistent and well-understood way to interact with data over the internet.</p>
<h2 id="heading-why-use-rest">Why Use REST?</h2>
<p>REST architectural principles offer a compelling set of advantages that contribute to building robust, scalable, and maintainable web services. Below are some of the key benefits that make REST a preferred choice for modern web development:</p>
<ul>
<li><p><strong>Simplicity and familiarity:</strong> REST leverages standard HTTP, which is already well-understood by developers and infrastructure.</p>
</li>
<li><p><strong>Scalability:</strong> The stateless nature of REST allows for easy scaling of both client and server components independently.</p>
</li>
<li><p><strong>Flexibility and interoperability:</strong> RESTful APIs can be consumed by a wide variety of clients, regardless of the technology stack.</p>
</li>
<li><p><strong>Cacheability:</strong> REST's design supports caching mechanisms, leading to improved performance and reduced server load.</p>
</li>
<li><p><strong>Loose coupling:</strong> The client and server are independent, allowing for changes on either side without necessarily affecting the other.</p>
</li>
<li><p><strong>Visibility and monitoring:</strong> The straightforward nature of HTTP requests and responses makes it easier to monitor and debug interactions.</p>
</li>
</ul>
<h2 id="heading-core-principles-of-rest-architecture">Core Principles of REST Architecture</h2>
<p>REST (Representational State Transfer) is built on a few simple principles that make APIs easy to understand and use. Here’s a quick breakdown of the key ones:</p>
<h3 id="heading-statelesness">Statelesness</h3>
<p>Every request from the client to the server must contain all the information needed to process it. The server doesn’t store anything about the client between requests – no session, no memory of previous actions.</p>
<p><strong>Example:</strong> If a user sends <code>GET /movies/1</code>, the server returns the movie data without needing to know whether the user is logged in or what they requested before.</p>
<p>This makes APIs easier to scale, since each request can be handled independently.</p>
<h3 id="heading-resource-and-uris">Resource and URIs</h3>
<p>In REST, everything you work with is considered a resource – users, products, and so on. Each resource should be accessible via a unique, meaningful URL.</p>
<p><strong>Example:</strong></p>
<ul>
<li><p><code>/movies</code> – a collection of movie resources</p>
</li>
<li><p><code>/movies/42</code> – a specific movie with ID 42</p>
</li>
</ul>
<p>Resources are treated like nouns. Actions are determined by the HTTP method used.</p>
<h3 id="heading-standard-http-methods">Standard HTTP Methods</h3>
<p>REST takes full advantage of HTTP methods to describe what action you’re taking on a resource:</p>
<ul>
<li><p><code>GET</code> – retrieve data</p>
</li>
<li><p><code>POST</code> – create a new resource</p>
</li>
<li><p><code>PUT</code> – update or replace a resource</p>
</li>
<li><p><code>PATCH</code> – partially update a resource</p>
</li>
<li><p><code>DELETE</code> – remove a resource</p>
</li>
</ul>
<p><strong>Example:</strong> To delete a movie, you’d send a <code>DELETE</code> request to <code>/movies/42</code>. That’s clear, consistent, and intuitive.</p>
<h3 id="heading-uniform-interface">Uniform Interface</h3>
<p>REST enforces a consistent structure for communication between client and server. This means all REST APIs should behave similarly, no matter who built them. It includes:</p>
<ul>
<li><p>Using URIs to identify resources</p>
</li>
<li><p>Using standard HTTP methods</p>
</li>
<li><p>Representing data in formats like JSON or XML</p>
</li>
<li><p>Self-descriptive messages (for example, proper status codes and headers)</p>
</li>
</ul>
<p>This consistency makes it easier for developers to understand and integrate with RESTful APIs.</p>
<h3 id="heading-cacheability">Cacheability</h3>
<p>Servers should label responses as cacheable (stored to be retrieved later) or not, so clients can reuse responses when appropriate. This reduces unnecessary server load and improves performance.</p>
<p><strong>Example:</strong> A <code>GET /movies</code> response can be cached for 5 minutes if the data doesn’t change frequently. That means fewer repeated calls for the same info.</p>
<h3 id="heading-client-server-separation">Client-Server Separation</h3>
<p>The client (frontend) and server (backend) operate independently. The client just needs to know how to communicate with the API – it doesn’t care how the server handles data, and vice versa.</p>
<p>This separation allows teams to develop and scale frontend and backend systems separately.</p>
<p>The principles above help create APIs that are scalable, predictable, and easy to work with.</p>
<h2 id="heading-how-to-build-a-simple-express-app">How to Build a Simple Express App</h2>
<h3 id="heading-what-is-express">What is Express?</h3>
<p>Express.js is a lightweight and flexible Node.js web application framework. Built on top of Node.js, it provides a robust set of features for building single-page, multi-page, and hybrid web applications and APIs. Think of it as a helpful toolkit that streamlines the process of setting up and managing web servers and routing requests.</p>
<p>In this exercise, you will be building an Express app that will:</p>
<ol>
<li><p>Handle a simple in-memory collection of movies as a RESTful resource</p>
</li>
<li><p>Support basic CRUD operations using the appropriate HTTP methods (GET, POST, PUT, DELETE)</p>
</li>
<li><p>Parse incoming JSON requests using built-in middleware</p>
</li>
<li><p>Use a custom middleware function to validate movie input before creating or updating entries</p>
</li>
<li><p>Send clear and meaningful responses based on the outcome of each request</p>
</li>
</ol>
<p>By the end, you’ll have a working API that follows REST principles and can be tested using a tool like Thunder Client or Postman.</p>
<h3 id="heading-set-up-the-express-app">Set Up the Express App</h3>
<p>To get the most out of this exercise, there are a few tools and concepts you should already be familiar with. Since we’re focusing on REST principles and how to apply them using Express, we won’t dive deep into the basics of these prerequisites. Make sure you’re comfortable with the following:</p>
<ul>
<li><p>Node.js</p>
</li>
<li><p>Npm</p>
</li>
<li><p>Thunderclient extension</p>
</li>
<li><p>Basic JavaScript</p>
</li>
</ul>
<p>With that, let’s get started.</p>
<p>Open your command prompt and create a new directory (folder):</p>
<pre><code class="lang-bash">mkdir express-app
</code></pre>
<p>Navigate into your new directory:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">cd</span> express-app
</code></pre>
<p>Initialize an npm project:</p>
<pre><code class="lang-bash">npm init -y
</code></pre>
<p>Install the Express package in your project:</p>
<pre><code class="lang-bash">npm install express
</code></pre>
<p>Now, open your directory in your code editor with the following command:</p>
<pre><code class="lang-bash">code .
</code></pre>
<p>Create a new file, server.js, and set up your Express app in that file:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>);
<span class="hljs-keyword">const</span> app = express();
app.use(express.json());

app.listen(<span class="hljs-number">8000</span>, <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Server running on port 8000'</span>));
</code></pre>
<p>This snippet above sets up a basic Express server. It starts by importing the Express library you installed, enables JSON parsing for incoming requests (so we can work with request bodies), and listens on port 3000. It’s ready to handle RESTful routes like <code>GET</code>, <code>POST</code>, <code>PUT</code>, and <code>DELETE</code> as we build out our API.</p>
<p>To start your server, go back to your command prompt and type in this command:</p>
<pre><code class="lang-bash">node server.js
</code></pre>
<p>You should see this logged in your command prompt:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1744840192457/818bc1a4-3e96-4494-9895-d02cf816e3f3.png" alt="A screenshot of a command prompt or terminal window. The prompt shows the current directory as &quot;C:sersSEResktopest-tutorial>&quot;. The command &quot;node server.js&quot; has been executed, and the output below it reads &quot;Server is running on port 8000&quot;." width="600" height="400" loading="lazy"></p>
<h3 id="heading-build-restful-resources">Build RESTful Resources</h3>
<p>With our Express app set up, let’s build out the <code>/movies</code> resource using RESTful routes. We'll treat each movie as a resource and use HTTP methods to define what we want to do – retrieve, add, update, or delete movies. For simplicity, we'll store the movies in an in-memory array.</p>
<p>Here is the full set of routes. Add it in your server.js file just under your <code>app.use(express.json());</code> line:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// In-memory database (for demonstration purposes)</span>
<span class="hljs-comment">// In a real application, you would use a database like MongoDB or PostgreSQL</span>
<span class="hljs-keyword">const</span> movies = [];

<span class="hljs-comment">// Get all movies</span>
app.get(<span class="hljs-string">'/movies'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  res.json(movies);
  <span class="hljs-built_in">console</span>.log(movies);
});

<span class="hljs-comment">// Get a particular movie by ID</span>
app.get(<span class="hljs-string">'/movies/:id'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> movie = movies.find(<span class="hljs-function"><span class="hljs-params">m</span> =&gt;</span> m.id === <span class="hljs-built_in">parseInt</span>(req.params.id));
  <span class="hljs-keyword">if</span> (!movie) <span class="hljs-keyword">return</span> res.status(<span class="hljs-number">404</span>).send(<span class="hljs-string">'Movie not found'</span>);
  res.json(movie);
});

<span class="hljs-comment">// Add a new movie</span>
app.post(<span class="hljs-string">'/movies'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> movie = {
    <span class="hljs-attr">id</span>: movies.length + <span class="hljs-number">1</span>,
    <span class="hljs-attr">title</span>: req.body.title,
    <span class="hljs-attr">genre</span>: req.body.genre,
    <span class="hljs-attr">year</span>: req.body.year
  };
  movies.push(movie);
  res.status(<span class="hljs-number">201</span>).json(movie);
});

<span class="hljs-comment">// Update a movie</span>
app.put(<span class="hljs-string">'/movies/:id'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> movie = movies.find(<span class="hljs-function"><span class="hljs-params">m</span> =&gt;</span> m.id === <span class="hljs-built_in">parseInt</span>(req.params.id));
  <span class="hljs-keyword">if</span> (!movie) <span class="hljs-keyword">return</span> res.status(<span class="hljs-number">404</span>).send(<span class="hljs-string">'Movie not found'</span>);

  movie.title = req.body.title;
  movie.genre = req.body.genre;
  movie.year = req.body.year;

  res.json(movie);
});

<span class="hljs-comment">// Delete a movie</span>
app.delete(<span class="hljs-string">'/movies/:id'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> movieIndex = movies.findIndex(<span class="hljs-function"><span class="hljs-params">m</span> =&gt;</span> m.id === <span class="hljs-built_in">parseInt</span>(req.params.id));
  <span class="hljs-keyword">if</span> (movieIndex === <span class="hljs-number">-1</span>) <span class="hljs-keyword">return</span> res.status(<span class="hljs-number">404</span>).send(<span class="hljs-string">'Movie not found'</span>);

  <span class="hljs-keyword">const</span> deletedMovie = movies.splice(movieIndex, <span class="hljs-number">1</span>);
  res.json(deletedMovie);
});
</code></pre>
<p>The code above defines a complete set of RESTful routes for managing a movies resource using Express.</p>
<p>It begins with an in-memory array, <code>movies</code>, which acts as our temporary data store. The <code>GET /movies</code> route returns all books, while <code>GET /movies/:id</code> looks up a book by its ID using <code>Array.find()</code>, returning a 404 status if it's not found. The <code>POST /movies</code> route accepts JSON input, creates a new book with an auto-incremented ID, and adds it to the array, returning the new resource with a <code>201 Created</code> status.</p>
<p>The <code>PUT /movies/:id</code> route handles full updates. It first finds the book, and if found, updates its <code>title</code> , <code>genre</code>, and <code>year</code> with the new values from the request body. The <code>DELETE /movies/:id</code> route removes a movie by finding its index in the array and using <code>splice()</code>. If the movie doesn't exist, both PUT and DELETE return a 404 error.</p>
<p>These routes demonstrate idempotency – that is, sending the same PUT or DELETE request multiple times will have the same effect as sending it once, a key REST principle. Each route also returns appropriate HTTP status codes and JSON responses, following REST conventions closely.</p>
<p>Each route follows a REST principle:</p>
<ul>
<li><p>Uses nouns for endpoints (<code>/movies</code>)</p>
</li>
<li><p>Uses standard HTTP methods to express actions</p>
</li>
<li><p>Ensure idempotency where appropriate (PUT, DELETE)</p>
</li>
<li><p>Return appropriate status codes and messages</p>
</li>
</ul>
<p>This structure keeps your API predictable and easy to use – exactly what REST is all about.</p>
<h3 id="heading-middlewares">Middlewares</h3>
<p>In RESTful APIs built with frameworks like Express, middleware plays a key role in maintaining clean, modular, and consistent request handling.</p>
<p>Middlewares are functions that sit in the middle of the request-response cycle in an Express app. When a client sends a request, middleware functions have access to the <code>req</code> (request), <code>res</code> (response), and <code>next</code> objects. They can inspect, modify, or act on the request before it reaches the route handler or even terminate the response early.</p>
<p>You have already seen a middleware here: <code>app.use(express.json());</code>. This is a global middleware that is used for parsing JSON. We will be creating a custom middleware for validating input for our POST and PUT requests.</p>
<p>Add the following code in your server.js file just before your routes:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Middleware for simple validation</span>
<span class="hljs-keyword">const</span> validateMovie = <span class="hljs-function">(<span class="hljs-params">req, res, next</span>) =&gt;</span> {
  <span class="hljs-keyword">if</span> (!req.body.title || !req.body.genre || !req.body.year) {
      <span class="hljs-keyword">return</span> res.status(<span class="hljs-number">400</span>).send(<span class="hljs-string">'Title, genre, and year are required'</span>);
  }
  next();
};
</code></pre>
<p>This middleware function, <code>validateMovie</code>, performs basic validation on incoming requests before they reach the route handler. It checks if the <code>title</code>, <code>genre</code>, and <code>year</code> fields are present in the request body. If any of these fields are missing, it immediately responds with a <code>400 Bad Request</code> status and an error message. If all required fields are provided, it calls <code>next()</code> to pass control to the next middleware or route. This keeps validation logic separate and reusable, helping maintain clean and RESTful route handlers.</p>
<p>To use this middleware, pass it as an argument in your POST and PUT routes, for example example:</p>
<pre><code class="lang-javascript">app.post(<span class="hljs-string">'/movies'</span>, validateMovie, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> movie = {
    <span class="hljs-attr">id</span>: movies.length + <span class="hljs-number">1</span>,
    <span class="hljs-attr">title</span>: req.body.title,
    <span class="hljs-attr">genre</span>: req.body.genre,
    <span class="hljs-attr">year</span>: req.body.year
  };
  movies.push(movie);
  res.status(<span class="hljs-number">201</span>).json(movie);
});
</code></pre>
<h3 id="heading-test-your-express-app">Test Your Express App</h3>
<p>To test the changes you have made, you need to restart your server. Go to your command prompt and press CTRL + C (for Windows) or Command + . (for MacOS). Input the start command like before to start the server again.</p>
<p>For this exercise, you will be testing the endpoints with the Thunder Client extension on VSCode. Thunder Client is a lightweight REST API extension for VSCode. With Thunder Client, you can your REST API routes and endpoints directly in VSCode.</p>
<p>To download Thunder Client, click on the Extension icon on the taskbar on your left and search “Thunder Client”. Then click Install:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1744234771851/a5d7a3e4-384b-47e9-8b2d-47bc45a2007d.png" alt="A screenshot of the Extensions Marketplace in Visual Studio Code (VS Code). The search bar at the top contains the text &quot;Thunder&quot;. Below the search bar, a list of extensions related to &quot;Thunder&quot; is displayed. The first result, &quot;Thunder Client,&quot; shows an install button. A red arrow points to the Extensions icon in the VS Code activity bar on the left, which is highlighted to indicate that this is the icon to click." width="600" height="400" loading="lazy"></p>
<p>After installation, you'll see the Thunder Client icon appear in your sidebar below the Extensions icon. Click it, then hit New Request to open a new tab. The request tab will open with a clean layout, ready for you to send and test API calls:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1744282644259/dfe4b735-c465-4993-bc46-cce28966deb3.png" alt="A screenshot of the Thunder Client interface within Visual Studio Code. A new request tab is open, displaying a GET request configured to the URL &quot;https://www.thunderclient.com/welcome&quot;. The HTTP method is set to &quot;GET&quot; in a dropdown menu. Below the URL bar, tabs for &quot;Query,&quot; &quot;Headers,&quot; &quot;Auth,&quot; &quot;Body,&quot; &quot;Tests,&quot; and &quot;Pre Run&quot; are visible, with &quot;Query&quot; currently selected, showing a section for &quot;Query Parameters&quot; with fields for &quot;parameter&quot; and &quot;value&quot;. At the bottom, a message indicates &quot;Non-Commercial Use&quot; with a link to view terms. The left sidebar shows &quot;THUNDER CLIENT&quot; with options like &quot;New Request,&quot; &quot;Activity,&quot; and &quot;Collections." class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>To start testing your API, set the request method (GET, POST, PUT, or DELETE) from the dropdown and enter the appropriate route, like <code>http://localhost:3000/movies</code>. For GET requests, just hit Send and you should see a response, in this case, an empty array <code>[]</code>. To get a specific movie, you include an ID (for example, <code>/movies/1</code>).</p>
<p>For <code>POST</code>, <code>PUT</code>, and <code>DELETE</code> requests, switch to the Body tab and select the JSON format. Then provide the data you want to send:</p>
<ul>
<li><p><strong>POST</strong> <code>/movies</code>: Add a new movie with <code>{"title": "Movie Title", "genre": "Genre Name", "year": 0000}</code>.</p>
</li>
<li><p><strong>PUT</strong> <code>/movies/1</code>: Update an existing movie with the same JSON structure.</p>
</li>
<li><p><strong>DELETE</strong> <code>/movies/1</code>: Remove a movie by its ID — no body is needed.</p>
</li>
</ul>
<p>After sending each request, Thunder Client will display the response body, headers, and status code. Example:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1744840699502/4ea83fbc-7b47-4aea-b8ff-a6e351bf54be.png" alt="A screenshot of the Thunder Client interface in Visual Studio Code, showing a successful POST request. On the left, the request details are visible: the HTTP method is set to &quot;POST&quot; with the URL &quot;http://localhost:8000/movies&quot;. The &quot;Body&quot; tab is selected, displaying JSON content: {&quot;title&quot;: &quot;Home Alone&quot;, &quot;genre&quot;: &quot;Comedy&quot;, &quot;year&quot;: 1999}. On the right, the response details indicate a &quot;Status: 201 Created&quot;, &quot;Size: 58 Bytes&quot;, and &quot;Time: 5 ms&quot;. The &quot;Response&quot; tab is selected, showing the JSON response: {&quot;id&quot;: 1, &quot;title&quot;: &quot;Home Alone&quot;, &quot;genre&quot;: &quot;Comedy&quot;, &quot;year&quot;: 1999}." width="600" height="400" loading="lazy"></p>
<h2 id="heading-bad-rest-practices-to-avoid">Bad REST Practices to Avoid</h2>
<p>When building REST APIs, aside from using the right HTTP methods, you also have to consider avoiding practices that break the core principles of REST. These bad practices can make your API harder to use, less predictable, or even misleading.</p>
<p>Here are some common REST bad practices and how to avoid them:</p>
<h3 id="heading-using-verbs-in-endpoints"><strong>Using verbs in endpoints</strong></h3>
<p>Avoid routes like <code>/getMovies</code> or <code>/createMovie</code>. RESTful APIs rely on HTTP methods to express actions, so use nouns for endpoints and let methods do the talking — for example, use <code>GET /movies</code> to retrieve movies and <code>POST /movie</code> to create one.</p>
<h3 id="heading-ignoring-http-status-codes"><strong>Ignoring HTTP status codes</strong></h3>
<p>Returning <code>200 OK</code> for every response, even errors, breaks REST conventions. Use the appropriate status codes: <code>201 Created</code> for successful POSTs, <code>404 Not Found</code> when a resource doesn’t exist, and <code>400 Bad Request</code> for validation issues. This helps clients interpret responses correctly.</p>
<h3 id="heading-overloading-a-single-endpoint"><strong>Overloading a single endpoint</strong></h3>
<p>Avoid writing one endpoint that changes behaviour based on the request body or headers. Each route should clearly map to a resource and method, like <code>GET /movies/1</code> to fetch, and <code>DELETE /movies/1</code> to remove, making the API predictable and easy to follow.</p>
<h3 id="heading-not-being-idempotent-where-expected"><strong>Not being idempotent where expected</strong></h3>
<p><code>PUT</code> and <code>DELETE</code> should be idempotent, meaning repeated requests should have the same effect. If calling <code>DELETE /movies/1</code> twice causes an error or unexpected behaviour, that’s a red flag. Design your handlers to handle these cases gracefully.</p>
<h3 id="heading-exposing-internal-logic-or-database-structure"><strong>Exposing internal logic or database structure</strong></h3>
<p>Don’t leak internal details like database table names or query logic in your route naming (<code>/api/movie_table_data</code>). Keep your URIs clean, abstracted, and centred around the actual resource, like <code>/movies</code>.</p>
<p>Avoiding these practices not only keeps your API RESTful but also improves developer experience, consistency, and long-term maintainability.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>You have explored the core ideas behind REST and put them into practice by building and testing a real Express API. This hands-on approach should help bridge the gap between theory and real-world application.</p>
<p>Along the way, you learned how REST treats resources, how to write clean and predictable routes, and why these principles matter when designing APIs that are easy to use and maintain.</p>
<p>Here’s a quick recap of what you’ve built and learned:</p>
<ul>
<li><p>Defined what REST is and why it’s widely used in web development</p>
</li>
<li><p>Explored core REST principles like statelessness, resource-based routing, HTTP methods, status codes, and idempotency</p>
</li>
<li><p>Set up a simple Express server to serve as the base for a RESTful API</p>
</li>
<li><p>Built a complete set of routes (GET, POST, PUT, DELETE) for managing a <code>movies</code> resource</p>
</li>
<li><p>Used middleware for tasks like JSON parsing and input validation</p>
</li>
<li><p>Tested routes using Thunder Client and learned how to interact with each HTTP method</p>
</li>
<li><p>Identified common REST anti-patterns and how to avoid them for cleaner design</p>
</li>
</ul>
<p>To take your API further and follow more advanced RESTful practices, consider:</p>
<ul>
<li><p>Organising routes with Express Router to keep your code modular</p>
</li>
<li><p>Adding robust error handling to return consistent and informative responses</p>
</li>
<li><p>Using logging tools like <code>morgan</code> to monitor requests and debug more easily</p>
</li>
<li><p>Securing endpoints with authentication methods like JWT or API keys</p>
</li>
<li><p>Structuring responses consistently, possibly with pagination and filtering for larger datasets</p>
</li>
<li><p>Validating user input thoroughly with libraries like <code>Joi</code> or <code>express-validator</code></p>
</li>
</ul>
<p>Explore the full project on <a target="_blank" href="https://github.com/oliverTwist2/rest-tutorial">GitHub</a>, review the code, and try extending it with your features. Happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Learn API Fundamentals and Architecture – A Beginner-Friendly Guide ]]>
                </title>
                <description>
                    <![CDATA[ Here are some questions for you: How do you log in to apps with your Google, Apple, or Microsoft account? How do online payments with Paystack or PayPal work? How do apps like Facebook and Instagram share information and notifications? The answer is:... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/learn-api-fundamentals-and-architecture/</link>
                <guid isPermaLink="false">67dd93c136028f6326576025</guid>
                
                    <category>
                        <![CDATA[ APIs ]]>
                    </category>
                
                    <category>
                        <![CDATA[ architecture ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ikegah Oliver ]]>
                </dc:creator>
                <pubDate>Fri, 21 Mar 2025 16:28:49 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1742310491936/3e9eb6e8-9f7d-424a-821e-b7110e3cf2f0.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Here are some questions for you: How do you log in to apps with your Google, Apple, or Microsoft account? How do online payments with Paystack or PayPal work? How do apps like Facebook and Instagram share information and notifications?</p>
<p>The answer is: they use APIs. These are powerful tools that drive mobile and web development and a wide range of applications, including cloud services, IoT devices, desktop software, and more.</p>
<p>APIs enable communication between applications, facilitating data exchange and verification.</p>
<p>In this article, you’ll learn all about APIs: the different types, their architecture, and the tradeoffs between the different architectures.</p>
<h3 id="heading-heres-what-well-cover">Here’s what we’ll cover:</h3>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-is-an-api">What is an API?</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-how-do-apis-work">How Do APIs Work?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-why-are-apis-important">Why Are APIs Important?</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-types-of-apis">Types of APIs</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-open-apis">Open APIs</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-partner-apis">Partner APIs</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-internal-apis">Internal APIs</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-composite-apis">Composite APIs</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-types-of-api-architecture">Types of API Architecture</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-rest-apis">REST APIs</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-soap-apis">SOAP APIs</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-graphql-apis">GraphQL APIs</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-grpc-apis">gRPC APIs</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-choose-an-api-architecture">How to Choose an API Architecture</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion-and-future-trends">Conclusion and Future Trends</a></p>
</li>
</ul>
<p>This article is well-suited for beginners in web and mobile development and developers seeking a concise understanding of APIs and how they function.</p>
<h2 id="heading-what-is-an-api">What is an API?</h2>
<p>API stands for Application Programming Interface. It is a set of rules and protocols that lets different software systems communicate with each other. An API defines how applications request services and exchange data, acting as a clear contract between a client and a server.</p>
<p>APIs simplify complex code into simple commands, letting developers connect systems and use built-in features without needing to know all the internal workings.</p>
<h3 id="heading-how-do-apis-work">How Do APIs Work?</h3>
<p>Imagine a restaurant: the customer (client) orders food through the waiter (API), who then communicates the order to the kitchen (server). The kitchen prepares the meal and sends it back through the waiter to the customer. Just like the waiter, the API handles requests and responses, letting the customer enjoy the meal without needing to know the details of the kitchen's operations.</p>
<p>A more practical example is when you buy a subscription online, and your payment information is securely sent to Paystack through its payment API. The API is a middleman that takes your request, verifies and processes your payment details with the bank, and then returns a confirmation to the website without directly exposing sensitive data.</p>
<p>Technically, a client initiates a request aimed at a server, specifying either data retrieval or procedural execution. Upon receiving and authenticating this request, the API performs the required operations. Then the API sends a response to the client, including the request's outcome (success or failure) and any requested data elements.</p>
<p><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXeho5OxXyKdS_-Sam70CtbZIH6y1wFMH3r21I0ZeNDVFNqoY0Jr2Lk5u_FfsiIas6LEnMPjRbQticIaDZi0iCF93Zj-JpxjZzXrwEGtdS_vIopXEUtNG5mvVHnVpf5vvhZGHw4Q?key=2qCWq-hs7d172uM7WbtEHg_B" alt="Diagram from shiksha.com illustrating how an API works." width="600" height="400" loading="lazy"></p>
<h3 id="heading-why-are-apis-important">Why Are APIs Important?</h3>
<p>APIs are crucial in software development because they make connecting different applications and services easier. They let you integrate external functionalities without building everything from scratch, saving time and reducing complexity through standardised commands.</p>
<p>For users, APIs also enhance security and user experience. They serve as secure gateways that filter data exchange between apps and external services, protecting sensitive information while ensuring smooth, reliable interactions.</p>
<h2 id="heading-types-of-apis">Types of APIs</h2>
<p>API types are mainly categorised by their accessibility and usage. There are four types of APIs, namely:</p>
<ol>
<li><p>Open (Public) APIs</p>
</li>
<li><p>Partner APIs</p>
</li>
<li><p>Internal (Private) APIs</p>
</li>
<li><p>Composite APIs</p>
</li>
</ol>
<h3 id="heading-open-apis">Open APIs</h3>
<p>Open APIs are APIs made available to the general public. This encourages developers, organisations, and other people to use them to develop applications, integrate them into their services, and improve them. Open APIs provide standardised access to data or services over the Internet.</p>
<p>Some very useful Open APIs include:</p>
<ul>
<li><p><a target="_blank" href="https://tradewatch.io/">TradeWatch</a> – Real-time financial market data</p>
</li>
<li><p><a target="_blank" href="http://serpapi.com">SerpAPI’s Search API</a> – Real-time Google SERP API</p>
</li>
<li><p><a target="_blank" href="http://twitterapi.io">TwitterApi.io</a> – Access real-time and historical data</p>
</li>
<li><p><a target="_blank" href="https://instagram-posts-generator.vercel.app/">Instagram Post Generator</a> – Generate posts with templates from popular IG pages</p>
</li>
</ul>
<h3 id="heading-partner-apis">Partner APIs</h3>
<p>Partner APIs are shared with specific business partners and often require authentication and agreements. They perform essential functions for businesses and applications.</p>
<p>For example, a payment API like Paystack directly communicates with service providers and banking platforms to process payments for products and services.</p>
<h3 id="heading-internal-apis">Internal APIs</h3>
<p>Internal APIs are used for internal communication within an organisation. They enable integration and streamline internal processes. Internal teams use the API to access and share data between their applications. The API is not exposed to the public, ensuring that sensitive business logic remains secure.</p>
<p>An example is a company’s internal API that connects its HR, payroll, and project management systems.</p>
<h3 id="heading-composite-apis">Composite APIs</h3>
<p>Composite APIs combine multiple API calls into a single request. They are instrumental in microservices architectures, where a single operation may require data from several services. A single API call triggers requests to multiple underlying APIs, and the composite API then combines the responses and returns a unified result.</p>
<p>For example, an e-commerce platform might use a composite API to fetch product details, pricing, and inventory information in one go, reducing latency and simplifying the integration process.</p>
<h2 id="heading-types-of-api-architecture">Types of API Architecture</h2>
<p>APIs are structured differently depending on use case, scalability, security, and accessibility. There are multiple ways to structure an API, but we will only focus on the most prevalent architectural styles used in Web development. They include:</p>
<ol>
<li><p>REST</p>
</li>
<li><p>SOAP</p>
</li>
<li><p>GraphQL</p>
</li>
<li><p>gRPC</p>
</li>
</ol>
<h3 id="heading-rest-apis">REST APIs</h3>
<p>Representational State Transfer (REST) is an architectural style that uses HTTP methods (POST, GET, PUT, DELETE) to perform CRUD (Create, Read, Update, Delete) operations on resource-based URIs.</p>
<p>REST APIs are built with frameworks like Express.js (Node.js), Django/Flask (Python), and Spring Boot (Java).</p>
<h4 id="heading-key-components">Key Components</h4>
<ol>
<li><p>Resources and endpoints:</p>
<ul>
<li><p>The entities exposed by the API can include anything: users, products, documents, and so on.</p>
</li>
<li><p>Each resource is identified by a unique URI (Uniform Resource Identifier).</p>
</li>
</ul>
</li>
<li><p>HTTP methods:</p>
<ul>
<li><p>GET: Retrieves a resource.</p>
</li>
<li><p>POST: Creates a new resource.</p>
</li>
<li><p>PUT: Updates an existing resource.</p>
</li>
<li><p>DELETE: Removes a resource.</p>
</li>
<li><p>PATCH: Partially updates an existing resource.</p>
</li>
</ul>
</li>
<li><p>Data representation:</p>
<ul>
<li><p>Resources can have multiple representations (for example, JSON, XML).</p>
</li>
<li><p>The API responds with the requested representation, allowing data to be structured and parsed easily.</p>
</li>
</ul>
</li>
<li><p>HTTP headers and query parameters:</p>
<ul>
<li><p>HTTP headers provide additional information about the request or response.</p>
</li>
<li><p>They can be used for authentication, content negotiation, and other purposes.</p>
</li>
</ul>
</li>
<li><p>Statelessness:</p>
<ul>
<li><p>Each request from a client to a server must contain all the information needed to understand and process the request.</p>
</li>
<li><p>The server does not store any client state between requests.</p>
</li>
</ul>
</li>
</ol>
<p>Other notable components are cacheability, HTTP Status, and HATEOAS. Together, these components define the structure and behaviour of RESTful systems, enabling seamless and efficient communication between clients and servers.</p>
<h4 id="heading-operation-overview">Operation Overview</h4>
<p>REST APIs expose resources through unique URIs and let clients perform operations using HTTP methods such as GET, POST, PUT, DELETE, and PATCH. Clients can request data in various formats, such as JSON or XML, and include additional details through HTTP headers and query parameters.</p>
<p>Each request is stateless and contains all the information required for processing without relying on stored client data. The API also uses HTTP status codes, cacheability, and HATEOAS to manage responses and guide further interactions, ensuring a seamless and efficient communication framework between clients and servers.</p>
<p><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXcYW8ovzOrZJB1eV1X82hvfuddZwjl7mwI56bYpZKCvzf4I4tNEfx58lhIjs_GMRaei9mXAxR78BUAIacBYoCw4J-CmkVKRDGa5ruK4KdYnmBV2Y0u9qz9QjOYSWNHBmUIPsopXuA?key=2qCWq-hs7d172uM7WbtEHg_B" alt="Diagram from apisec.ai illustrating the flow of a REST API, including endpoints, HTTP methods, and data exchange between client and server." width="600" height="400" loading="lazy"></p>
<h4 id="heading-practical-example-and-real-world-use-cases">Practical Example and Real-world Use Cases</h4>
<p>To illustrate how REST APIs work in practice, let’s consider a Book API that lets users manage a collection of books. Our example API has been created using the <a target="_blank" href="https://www.freecodecamp.org/news/get-started-with-nodejs/">NodeJS</a> and <a target="_blank" href="https://expressjs.com/">ExpressJS</a> frameworks. I won’t explain how these frameworks actually work here, as that’s beyond the scope of this article. So if you don’t understand the syntax in the code below, don’t worry – just focus on the <strong>Requests</strong> and <strong>Responses</strong> logic.</p>
<p>This API follows REST principles by using standard HTTP methods to perform CRUD (Create, Read, Update, Delete) operations:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> express = <span class="hljs-built_in">require</span>(<span class="hljs-string">"express"</span>); <span class="hljs-keyword">const</span> bodyParser = <span class="hljs-built_in">require</span>(<span class="hljs-string">"body-parser"</span>);
<span class="hljs-keyword">const</span> app = express(); app.use(bodyParser.json());

<span class="hljs-keyword">const</span> app = express();
app.use(bodyParser.json());

<span class="hljs-comment">// Dummy Database</span>
<span class="hljs-keyword">let</span> books = [
  { <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">title</span>: <span class="hljs-string">"The Pragmatic Programmer"</span>, <span class="hljs-attr">author</span>: <span class="hljs-string">"Andy Hunt"</span> },
  { <span class="hljs-attr">id</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">title</span>: <span class="hljs-string">"Clean Code"</span>, <span class="hljs-attr">author</span>: <span class="hljs-string">"Robert C. Martin"</span> },
];

<span class="hljs-comment">// GET all books (Client requests, Server responds)</span>
app.get(<span class="hljs-string">"/books"</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> res.json(books));

<span class="hljs-comment">// GET a single book by ID</span>
app.get(<span class="hljs-string">"/books/:id"</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> book = books.find(<span class="hljs-function">(<span class="hljs-params">b</span>) =&gt;</span> b.id === <span class="hljs-built_in">parseInt</span>(req.params.id));
  book ? res.json(book) : res.status(<span class="hljs-number">404</span>).json({ <span class="hljs-attr">message</span>: <span class="hljs-string">"Not found"</span> });
});

<span class="hljs-comment">// POST a new book (Client sends data, Server updates database)</span>
app.post(<span class="hljs-string">"/books"</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> newBook = { <span class="hljs-attr">id</span>: books.length + <span class="hljs-number">1</span>, ...req.body };
  books.push(newBook);
  res.status(<span class="hljs-number">201</span>).json(newBook);
});

<span class="hljs-comment">// PUT (Update) a book</span>
app.put(<span class="hljs-string">"/books/:id"</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> book = books.find(<span class="hljs-function">(<span class="hljs-params">b</span>) =&gt;</span> b.id === <span class="hljs-built_in">parseInt</span>(req.params.id));
  <span class="hljs-keyword">if</span> (book) {
    <span class="hljs-built_in">Object</span>.assign(book, req.body);
    res.json(book);
  } <span class="hljs-keyword">else</span> {
    res.status(<span class="hljs-number">404</span>).json({ <span class="hljs-attr">message</span>: <span class="hljs-string">"Not found"</span> });
  }
});

<span class="hljs-comment">// DELETE a book</span>
app.delete(<span class="hljs-string">"/books/:id"</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> index = books.findIndex(<span class="hljs-function">(<span class="hljs-params">b</span>) =&gt;</span> b.id === <span class="hljs-built_in">parseInt</span>(req.params.id));
  <span class="hljs-keyword">if</span> (index !== <span class="hljs-number">-1</span>) {
    books.splice(index, <span class="hljs-number">1</span>);
    res.json({ <span class="hljs-attr">message</span>: <span class="hljs-string">"Deleted"</span> });
  } <span class="hljs-keyword">else</span> {
    res.status(<span class="hljs-number">404</span>).json({ <span class="hljs-attr">message</span>: <span class="hljs-string">"Not found"</span> });
  }
});

app.listen(<span class="hljs-number">3000</span>, <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"API running on port 3000"</span>));
</code></pre>
<p>Here’s what’s going on in this code:</p>
<ul>
<li><p>Client sends a request: A user (or frontend app) requests data using HTTP methods like GET, POST, PUT, or DELETE. Example: GET <code>/books</code> requests all books or POST <code>/books</code> posts a new book to the database.</p>
</li>
<li><p>Server processes the request: The server receives the request, looks up the data (for example, from a database or in-memory array), and processes it.</p>
</li>
<li><p>Server sends a response: The server sends back a JSON response containing the requested data or a confirmation message. Here’s an example:</p>
</li>
</ul>
<pre><code class="lang-json">[
  { <span class="hljs-attr">"id"</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">"title"</span>: <span class="hljs-string">"The Pragmatic Programmer"</span>, <span class="hljs-attr">"author"</span>: <span class="hljs-string">"Andy Hunt"</span> },
  { <span class="hljs-attr">"id"</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">"title"</span>: <span class="hljs-string">"Clean Code"</span>, <span class="hljs-attr">"author"</span>: <span class="hljs-string">"Robert C. Martin"</span> }
]
</code></pre>
<ul>
<li>Client receives and uses the data: The frontend or another service consumes the API response and displays or processes it accordingly.</li>
</ul>
<p>Teams utilize REST APIs for web services, mobile apps, and cloud integrations. Social media platforms fetch posts, while e-commerce sites retrieve product details. Payment gateways process transactions and weather apps access real-time forecasts. REST’s simplicity and scalability make it the preferred choice for public and internal APIs.</p>
<h3 id="heading-soap-apis">SOAP APIs</h3>
<p>The Simple Object Access Protocol (SOAP) uses XML for messaging and includes built-in standards for security, transactions, and error handling. Its formal contract is defined by a WSDL (Web Services Description Language).</p>
<p>This architecture prioritises security and reliability through features like WS-Security and transaction management, making it suitable for complex enterprise applications that require rigid standards and robust error handling.</p>
<p>SOAP APIs are created using frameworks or tools such as Apache CXF, .NET WCF, and JAX-WS (Java).</p>
<h4 id="heading-key-components-1">Key Components</h4>
<ol>
<li><p>SOAP envelope:</p>
<ul>
<li><p>This is the root element of a SOAP message and defines the overall structure of the XML document.</p>
</li>
<li><p>It contains the SOAP Header and SOAP Body.</p>
</li>
</ul>
</li>
<li><p>SOAP body:</p>
<ul>
<li><p>This section contains the actual data being exchanged between the client and server.</p>
</li>
<li><p>It includes the request or response messages, which are typically structured as XML elements.</p>
</li>
</ul>
</li>
<li><p>WSDL (Web Services Description Language):</p>
<ul>
<li><p>This is an XML document that describes the web service, including its operations, message formats, and data types.</p>
</li>
<li><p>It acts as a contract between the client and server, outlining how to interact with the API.</p>
</li>
</ul>
</li>
<li><p>SOAP processor:</p>
<ul>
<li><p>This is the software component that processes SOAP messages.</p>
</li>
<li><p>It parses the XML document, extracts the relevant data, and performs the requested operation.</p>
</li>
</ul>
</li>
</ol>
<p>There is also the SOAP Endpoint, which is the URL where the SOAP service can be accessed, and the XML Schema (XSD), which defines the structure and data types used in the SOAP message's XML.</p>
<h4 id="heading-operation-overview-1">Operation Overview</h4>
<p>SOAP APIs operate by encapsulating data within an XML-based structure defined by a SOAP Envelope, which contains both a Header for metadata and a Body for the actual request or response information. The Body carries the exchange data, while a WSDL document serves as a contract detailing the service's operations, message formats, and data types.</p>
<p>A SOAP Processor then parses the XML, extracts relevant data, and executes the requested operations according to rules defined by an accompanying XML Schema (XSD). Communication with the service occurs through a specific SOAP Endpoint, ensuring a standardised, interoperable framework for web service interactions.</p>
<p><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXfN_kg7EZxppR62_usgGiNO7jTLWnrmd5MYzxLUyjl6cNSuVHBAVV-kWvQN2xZ5s1acOugK8SfGb2JKtIys01yMSrdRO7iwNCtc5CHh6QDDCBWH2vc7EYOiHNgpbyZv8jZBhTwejg?key=2qCWq-hs7d172uM7WbtEHg_B" alt="Diagram from muledreamin.com illustrating the flow of a SOAP API, including HTTP transfer, and data exchange between SOAP sender and SOAP receive." width="600" height="400" loading="lazy"></p>
<h4 id="heading-practical-examples-and-real-world-use-cases">Practical Examples and Real-world Use Cases</h4>
<p>To illustrate SOAP APIs and how they work practically, let’s consider a SOAP-based Banking Service API that provides secure operations for managing accounts and transactions. SOAP APIs use XML messaging to ensure secure and structured communication between systems. Creating a SOAP API and XML messaging is beyond the scope of this article, so here we’ll just focus on the Request and Response logic.</p>
<p>How it works:</p>
<ul>
<li><strong>Retrieve account information</strong>: The client sends an XML request to fetch a user’s account details:</li>
</ul>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">soapenv:Envelope</span> <span class="hljs-attr">xmlns:soapenv</span>=<span class="hljs-string">"http://schemas.xmlsoap.org/soap/envelope/"</span>
                  <span class="hljs-attr">xmlns:bank</span>=<span class="hljs-string">"http://example.com/bank"</span>&gt;</span>
   <span class="hljs-tag">&lt;<span class="hljs-name">soapenv:Header</span>/&gt;</span>
   <span class="hljs-tag">&lt;<span class="hljs-name">soapenv:Body</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">bank:GetAccountDetails</span>&gt;</span>
         <span class="hljs-tag">&lt;<span class="hljs-name">bank:AccountNumber</span>&gt;</span>123456789<span class="hljs-tag">&lt;/<span class="hljs-name">bank:AccountNumber</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">bank:GetAccountDetails</span>&gt;</span>
   <span class="hljs-tag">&lt;/<span class="hljs-name">soapenv:Body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">soapenv:Envelope</span>&gt;</span>
</code></pre>
<p>The server responds with an XML message containing the account details:</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">soapenv:Envelope</span> <span class="hljs-attr">xmlns:soapenv</span>=<span class="hljs-string">"http://schemas.xmlsoap.org/soap/envelope/"</span>&gt;</span>
   <span class="hljs-tag">&lt;<span class="hljs-name">soapenv:Body</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">GetAccountDetailsResponse</span>&gt;</span>
         <span class="hljs-tag">&lt;<span class="hljs-name">AccountNumber</span>&gt;</span>123456789<span class="hljs-tag">&lt;/<span class="hljs-name">AccountNumber</span>&gt;</span>
         <span class="hljs-tag">&lt;<span class="hljs-name">Balance</span>&gt;</span>5000.00<span class="hljs-tag">&lt;/<span class="hljs-name">Balance</span>&gt;</span>
         <span class="hljs-tag">&lt;<span class="hljs-name">Currency</span>&gt;</span>USD<span class="hljs-tag">&lt;/<span class="hljs-name">Currency</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">GetAccountDetailsResponse</span>&gt;</span>
   <span class="hljs-tag">&lt;/<span class="hljs-name">soapenv:Body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">soapenv:Envelope</span>&gt;</span>
</code></pre>
<ul>
<li><p><strong>Process a money transfer</strong>: The client submits a transfer request with authentication details:</p>
<pre><code class="lang-xml">  <span class="hljs-tag">&lt;<span class="hljs-name">soapenv:Envelope</span> <span class="hljs-attr">xmlns:soapenv</span>=<span class="hljs-string">"http://schemas.xmlsoap.org/soap/envelope/"</span>
                    <span class="hljs-attr">xmlns:bank</span>=<span class="hljs-string">"http://example.com/bank"</span>&gt;</span>
     <span class="hljs-tag">&lt;<span class="hljs-name">soapenv:Header</span>/&gt;</span>
     <span class="hljs-tag">&lt;<span class="hljs-name">soapenv:Body</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">bank:TransferFunds</span>&gt;</span>
           <span class="hljs-tag">&lt;<span class="hljs-name">bank:FromAccount</span>&gt;</span>123456789<span class="hljs-tag">&lt;/<span class="hljs-name">bank:FromAccount</span>&gt;</span>
           <span class="hljs-tag">&lt;<span class="hljs-name">bank:ToAccount</span>&gt;</span>987654321<span class="hljs-tag">&lt;/<span class="hljs-name">bank:ToAccount</span>&gt;</span>
           <span class="hljs-tag">&lt;<span class="hljs-name">bank:Amount</span>&gt;</span>100.00<span class="hljs-tag">&lt;/<span class="hljs-name">bank:Amount</span>&gt;</span>
           <span class="hljs-tag">&lt;<span class="hljs-name">bank:Currency</span>&gt;</span>USD<span class="hljs-tag">&lt;/<span class="hljs-name">bank:Currency</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">bank:TransferFunds</span>&gt;</span>
     <span class="hljs-tag">&lt;/<span class="hljs-name">soapenv:Body</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">soapenv:Envelope</span>&gt;</span>
</code></pre>
<p>  If successful, the server returns a confirmation response:</p>
<pre><code class="lang-xml">  <span class="hljs-tag">&lt;<span class="hljs-name">soapenv:Envelope</span> <span class="hljs-attr">xmlns:soapenv</span>=<span class="hljs-string">"http://schemas.xmlsoap.org/soap/envelope/"</span>&gt;</span>
     <span class="hljs-tag">&lt;<span class="hljs-name">soapenv:Body</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">TransferFundsResponse</span>&gt;</span>
           <span class="hljs-tag">&lt;<span class="hljs-name">Status</span>&gt;</span>Success<span class="hljs-tag">&lt;/<span class="hljs-name">Status</span>&gt;</span>
           <span class="hljs-tag">&lt;<span class="hljs-name">TransactionID</span>&gt;</span>TXN987654<span class="hljs-tag">&lt;/<span class="hljs-name">TransactionID</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">TransferFundsResponse</span>&gt;</span>
     <span class="hljs-tag">&lt;/<span class="hljs-name">soapenv:Body</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">soapenv:Envelope</span>&gt;</span>
</code></pre>
</li>
</ul>
<p>Banks, healthcare providers, and government agencies use SOAP for secure, reliable APIs. Financial institutions process transactions with strict authentication, while healthcare systems exchange patient data under compliance regulations. Airlines rely on SOAP for booking and ticketing, ensuring consistent data integrity across systems.</p>
<h3 id="heading-graphql-apis">GraphQL APIs</h3>
<p>GraphQL is a query language and runtime for APIs developed by Facebook. It allows clients to request exactly the data they need in a single request, reducing over-fetching and under-fetching.</p>
<h4 id="heading-key-components-2">Key Components</h4>
<ol>
<li><p>Schema: This is the heart of a GraphQL API. It defines the structure of your data, including the types of objects, their fields, and their relationships. It acts as a contract between the client and server, specifying what data can be queried.</p>
</li>
<li><p>Types: These define the structure of objects in your data. They specify the fields that each object has and the data types of those fields.</p>
</li>
<li><p>Fields: These are the individual pieces of data that can be queried on an object.</p>
</li>
<li><p>Queries: These are requests from the client to retrieve data. They specify the fields that the client wants to recover.</p>
</li>
<li><p>Mutations: These are requests from the client to modify data (create, update, or delete).</p>
</li>
<li><p>Resolvers: These are functions that fetch the data for each field in the schema. They connect the GraphQL schema to the underlying data sources.</p>
</li>
<li><p>Subscriptions: These enable real-time updates. Clients can subscribe to specific events, and the server will push updates whenever they occur.</p>
</li>
</ol>
<h4 id="heading-operation-overview-2">Operation Overview</h4>
<p>GraphQL defines a schema that specifies available data types and their relationships. Clients then construct queries or mutations that precisely request the needed data fields. The GraphQL server processes these requests, using resolvers to fetch data from backend sources.</p>
<p>The server validates the request against the schema, executes the resolvers, and returns a JSON response containing only the requested data. Clients can establish subscriptions for real-time updates, enabling the server to push data changes as they occur. This approach minimises over-fetching and under-fetching, improving efficiency and flexibility in data retrieval.</p>
<p><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXcmC7u4hu44TvJ603f9ODRYIgi3UiHMs-Q4qjE8FZqwPnEGDPTU6DhZSvLCZU3BO7WITNnuls_801ChJyACz6xpKOdvoQ5hLswAMIHZ3-Ii4dyg7CEKZ5m1AAgv70sso-c26Cl_sQ?key=2qCWq-hs7d172uM7WbtEHg_B" alt="Diagram from kinsta.com illustrating a GraphQL server architecture, showing the transfer of GraphQL Query request and JSON payload from the server." width="600" height="400" loading="lazy"></p>
<h4 id="heading-practical-examples-and-real-world-use-cases-1">Practical Examples and Real-world Use Cases</h4>
<p>Let’s explore how GraphQL APIs work practically by considering an E-commerce API powered by GraphQL. This API can efficiently fetch product details, reviews, and stock availability. The server is created using NodeJS and <a target="_blank" href="https://www.apollographql.com/docs/apollo-server">Apollo Server</a>. Creating the server is beyond the scope of this article, so we will focus on the Schema (how a relational database is structured and visually represented) and the <strong>Request</strong> and <strong>Response</strong> logic.</p>
<ol>
<li>Schema:</li>
</ol>
<pre><code class="lang-graphql"><span class="hljs-comment"># Schema (schema.graphql)</span>

<span class="hljs-keyword">type</span> Product {
  <span class="hljs-symbol">id:</span> ID!
  <span class="hljs-symbol">name:</span> String!
  <span class="hljs-symbol">description:</span> String
  <span class="hljs-symbol">price:</span> Float!
  <span class="hljs-symbol">inventory:</span> Int!
  <span class="hljs-symbol">category:</span> String!
}

<span class="hljs-keyword">type</span> Query {
  product(<span class="hljs-symbol">id:</span> ID!): Product
  products(<span class="hljs-symbol">category:</span> String): [Product!]!
}

<span class="hljs-keyword">type</span> Mutation {
  createProduct(<span class="hljs-symbol">name:</span> String!, <span class="hljs-symbol">description:</span> String, <span class="hljs-symbol">price:</span> Float!, <span class="hljs-symbol">inventory:</span> Int!, <span class="hljs-symbol">category:</span> String!): Product!
  updateProductInventory(<span class="hljs-symbol">id:</span> ID!, <span class="hljs-symbol">inventory:</span> Int!): Product!
}
</code></pre>
<p>The Schema defines the data types (<code>Product</code>, <code>Query</code>, <code>Mutation</code>) and specifies the available queries (<code>product</code>, <code>products</code>), and mutations (<code>createProduct</code>, <code>updateProductInventory</code>). It uses the <a target="_blank" href="https://graphql.org/learn/schema/">GraphQL type system</a> (String, Int, Float, ID, [ ], !)</p>
<ol start="2">
<li><p>Requests and Response</p>
<ul>
<li><p>Fetching product data - A client requests specific product fields (for example, name, price, and description):</p>
<pre><code class="lang-graphql">  <span class="hljs-keyword">query</span> {
    product(<span class="hljs-symbol">id:</span> <span class="hljs-string">"123"</span>) {
      name
      price
      description
    }
  }
</code></pre>
<p>  If it is successful, the server responds with only the requested data:</p>
<pre><code class="lang-json">  {
    <span class="hljs-attr">"data"</span>: {
      <span class="hljs-attr">"product"</span>: {
        <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Wireless Headphones"</span>,
        <span class="hljs-attr">"price"</span>: <span class="hljs-number">99.99</span>,
        <span class="hljs-attr">"inStock"</span>: <span class="hljs-literal">true</span>
      }
    }
  }
</code></pre>
</li>
<li><p>Create a new product:</p>
<pre><code class="lang-graphql">  <span class="hljs-keyword">mutation</span> {
    createProduct(<span class="hljs-symbol">name:</span> <span class="hljs-string">"Mouse"</span>, <span class="hljs-symbol">price:</span> <span class="hljs-number">30</span>, <span class="hljs-symbol">inventory:</span> <span class="hljs-number">100</span>, <span class="hljs-symbol">category:</span> <span class="hljs-string">"Electronics"</span>) {
      id
      name
      price
    }
  }
</code></pre>
</li>
<li><p>Update product information:</p>
<pre><code class="lang-graphql">  <span class="hljs-keyword">mutation</span> {
    updateProduct(<span class="hljs-symbol">id:</span> <span class="hljs-string">"123"</span>, <span class="hljs-symbol">price:</span> <span class="hljs-number">89.99</span>) {
      name
      price
    }
  }
</code></pre>
<p>  If successful, the server returns the updated details:</p>
<pre><code class="lang-json">  {
    <span class="hljs-attr">"data"</span>: {
      <span class="hljs-attr">"updateProduct"</span>: {
        <span class="hljs-attr">"name"</span>: <span class="hljs-string">"Wireless Headphones"</span>,
        <span class="hljs-attr">"price"</span>: <span class="hljs-number">89.99</span>
      }
    }
  }
</code></pre>
</li>
</ul>
</li>
</ol>
<p>Companies like Facebook and Shopify use GraphQL for efficient, flexible APIs. E-commerce and social apps fetch only needed data, reducing over-fetching. Mobile apps optimize performance, while analytics tools aggregate complex data seamlessly.</p>
<h3 id="heading-grpc-apis">gRPC APIs</h3>
<p>Remote Procedure Call (gRPC) is a high-performance RPC framework that serialises structured data using HTTP/2 and Protocol Buffers. It supports synchronous and asynchronous communication and features like streaming.</p>
<p>HTTP/2 is the latest evolution of HTTP, designed with exciting features like binary framing, multiplexing, header compression, and server push to boost performance and reduce latency. gRPC takes full advantage of these capabilities, enabling quick, efficient, and simultaneous communication, which makes it a perfect fit for microservices and real-time applications.</p>
<h4 id="heading-key-components-3">Key Components</h4>
<ol>
<li><p>Service definition: This is defined in a .proto file. It specifies the services offered and the RPC methods available, acting as the contract between client and server.</p>
</li>
<li><p>Messages are data structures defined using Protocol Buffers, which efficiently serialise and deserialise data between systems.</p>
</li>
<li><p>Stubs: Auto-generated client and server code that lets the client call remote methods as if they were local and enables the server to implement the service logic.</p>
</li>
<li><p>Channels: These manage the connection between client and server, handling the underlying network communication.</p>
</li>
<li><p>RPC methods: gRPC supports different types of calls, including unary (single request-response), client streaming, server streaming, and bidirectional streaming, each suited for different use cases.</p>
</li>
<li><p>Interceptors and metadata: These provide mechanisms to add extra functionality, such as authentication, logging, and error handling, by attaching metadata to RPC calls.</p>
</li>
</ol>
<h4 id="heading-operation-overview-3">Operation Overview</h4>
<p>gRPC enables developers to define service contracts and message types in a .proto file with Protocol Buffers, serving as a blueprint for available RPC methods. The code generator produces client and server stubs, allowing remote procedures to be invoked like local functions, while channels manage HTTP/2-based network communication.</p>
<p>It supports unary, client streaming, server streaming, and bidirectional streaming for different data exchange patterns. Also, interceptors and metadata can be integrated for tasks like authentication and logging, keeping the system robust, secure, and efficient.</p>
<h4 id="heading-practical-examples-and-real-world-use-cases-2">Practical Examples and Real-world Use Cases</h4>
<p>Let’s consider a ride-sharing application that uses gRPC for fast communication between clients (mobile apps) and backend services. gRPC uses binary serialization via protocol buffers (Protobuf) instead of text-based formats like JSON or XML. This makes network communication significantly faster and more efficient.</p>
<ol>
<li>The .proto file defines the API structure:</li>
</ol>
<pre><code class="lang-json">syntax = <span class="hljs-string">"proto3"</span>;

service RideService {
  rpc RequestRide(RideRequest) returns (RideResponse);
  rpc StreamRideUpdates(RideUpdateRequest) returns (stream RideUpdate);
}

message RideRequest {
  string user_id = 1;
  string pickup_location = 2;
  string destination = 3;
}

message RideResponse {
  string ride_id = 1;
  string driver_name = 2;
  string car_model = 3;
}

message RideUpdate {
  string ride_id = 1;
  string status = 2;
  string driver_location = 3;
}

message RideUpdateRequest {
  string ride_id = 1;
}
</code></pre>
<p>When a client sends a <code>RideRequest</code>, it is serialized into a compact binary format using Protobuf. This reduces payload size, speeds up transmission, and improves efficiency. The server deserializes it back into a structured object before processing.</p>
<ol start="2">
<li><p>Request and Response:</p>
<ul>
<li><p>Requesting a ride: The client sends a ride request with the click of a button that entails:</p>
<pre><code class="lang-json">  {
    <span class="hljs-attr">"user_id"</span>: <span class="hljs-string">"U123"</span>,
    <span class="hljs-attr">"pickup_location"</span>: <span class="hljs-string">"Central Park"</span>,
    <span class="hljs-attr">"destination"</span>: <span class="hljs-string">"Times Square"</span>
  }
</code></pre>
<p>  The server responds with driver details:</p>
<pre><code class="lang-json">  {
    <span class="hljs-attr">"ride_id"</span>: <span class="hljs-string">"R456"</span>,
    <span class="hljs-attr">"driver_name"</span>: <span class="hljs-string">"John Doe"</span>,
    <span class="hljs-attr">"car_model"</span>: <span class="hljs-string">"Toyota Prius"</span>
  }
</code></pre>
<p>  You must be wondering why the requests and responses are displayed in JSON since gRPC doesn’t use text-based formats like JSON and XML. The compressed binary stream used in gRPC is not human-readable like JSON. It’s a compact, efficient encoding format that requires Protobuf deserialization under the hood to be understood. In compressed binary stream format, the request or response will look like this:</p>
<pre><code class="lang-markdown">  08 D2 04 12 0D 43 65 6E 74 72 61 6C 20 50 61 72 6B 1A 0B 54 69 6D 65 73 20 53 71 75 61 72 65
</code></pre>
</li>
<li><p>Streaming ride updates: Once a ride is assigned, the server streams real-time updates to the client:</p>
<pre><code class="lang-json">  {
    <span class="hljs-attr">"ride_id"</span>: <span class="hljs-string">"R456"</span>,
    <span class="hljs-attr">"status"</span>: <span class="hljs-string">"Driver on the way"</span>,
    <span class="hljs-attr">"driver_location"</span>: <span class="hljs-string">"5th Avenue"</span>
  }
</code></pre>
</li>
</ul>
</li>
</ol>
<p>Companies use gRPC for high-performance, real-time applications requiring efficient service communication. Tech giants like Google, Netflix, and Dropbox utilize gRPC for scalable microservices. Ride-sharing apps stream live driver locations, while fintech platforms manage secure, low-latency transactions. IoT systems and AI applications depend on gRPC for real-time data exchange and efficient interactions.</p>
<h2 id="heading-how-to-choose-an-api-architecture">How to Choose an API Architecture</h2>
<p>Selecting an API architecture involves balancing various factors, including performance, scalability, ease of use, and security, according to your project's specific needs.</p>
<p>REST is known for its simplicity and stateless design, which aids scalability and ease of use, but its security depends mainly on external measures like HTTPS and proper authentication mechanisms.</p>
<p>SOAP, while more complex, provides robust built-in security standards (like WS-Security) and reliable transactional support, making it suitable for enterprise environments.</p>
<p>GraphQL offers efficient data fetching and high performance by allowing clients to request only the data they need. Still, it may require additional security measures such as query depth limiting and proper authentication on the server side.</p>
<p>gRPC delivers exceptional performance and is ideal for microservices with real-time data needs. It leverages HTTP/2 and TLS for secure, efficient communication, though it has a steeper learning curve.</p>
<p>The table below summarises the features and tradeoffs between these architectures:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Feature</td><td>REST</td><td>SOAP</td><td>GraphQL</td><td>gRPC</td></tr>
</thead>
<tbody>
<tr>
<td>Performance</td><td>Moderate (Potential over-fetching of data)</td><td>Low</td><td>High</td><td>High</td></tr>
<tr>
<td>Scalability</td><td>High</td><td>Moderate</td><td>High</td><td>Very high (Efficient for microservices and real-time data)</td></tr>
<tr>
<td>Ease of use</td><td>Simple and widely adopted</td><td>Complex</td><td>Intuitive for clients (Server-side complexity may grow)</td><td>Steep learning curve</td></tr>
<tr>
<td>Security</td><td>Relies on external mechanisms (HTTPS, OAuth, and so on)</td><td>Strong built-in security via WS-Security and formal contracts</td><td>Requires additional measures (query validation, rate limiting)</td><td>High security with built-in TLS support and robust authentication protocols</td></tr>
</tbody>
</table>
</div><h2 id="heading-conclusion-and-future-trends">Conclusion and Future Trends</h2>
<p>APIs have become a mainstay in modern software development, facilitating seamless communication and data exchange between diverse applications. Their impact is undeniable, from public APIs that fuel innovation to private APIs that streamline internal processes.</p>
<p>Understanding the various API architectures, like REST, SOAP, GraphQL, and gRPC, empowers developers to select the optimal approach for their specific needs, balancing performance, scalability, and ease of use.</p>
<p>Looking ahead, the API landscape is set for exciting changes. With AI-driven APIs, decentralized architectures, and improved security measures, we’ll see new ways to build and interact with software. The continuous evolution of API standards and the growth of low-code/no-code platforms are making API development more accessible to everyone.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
