<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Maria Ferreira on Medium]]></title>
        <description><![CDATA[Stories by Maria Ferreira on Medium]]></description>
        <link>https://medium.com/@mariaferreira.developer?source=rss-e61f06fa3b81------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*JsCDZUH9wfGsdauQi10BkA@2x.jpeg</url>
            <title>Stories by Maria Ferreira on Medium</title>
            <link>https://medium.com/@mariaferreira.developer?source=rss-e61f06fa3b81------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 21:19:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mariaferreira.developer/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Code Efficiently: External APIs Integration]]></title>
            <link>https://javascript.plainenglish.io/how-to-code-efficiently-external-apis-integration-9ceccaa6244f?source=rss-e61f06fa3b81------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ceccaa6244f</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[debugging]]></category>
            <dc:creator><![CDATA[Maria Ferreira]]></dc:creator>
            <pubDate>Fri, 17 Oct 2025 13:00:24 GMT</pubDate>
            <atom:updated>2025-10-19T04:52:24.057Z</atom:updated>
            <content:encoded><![CDATA[<p>Lately I have been spending more time on the backend than ever before. I am tackling a bit of everything: mTLS requests, object-oriented design, prompt engineering, internal API connections/creation, external API integrations… and being honest, I am loving it.</p><p>The only bad part is when the ticket is about <strong>badly documented external APIs</strong>. Just last month, I took on a card where the 404 Not Found error was actually nested inside a 200 OK response — some kind of badly implemented proxy.</p><p>These kind of moments have pushed me to start documenting my own process for integration…</p><blockquote>What should I do to figure out tricky situations and do not be 3 weeks with the same PR open?</blockquote><p>And <em>right</em> <em>after</em> 3-bad-integrations-experience, I took this notes:</p><h3>Step 1: External API? Test first, code later</h3><p>The most efficient way to handle poorly documented or discover before a lot of work that it is deprecated or so, is to <strong>test the API using cURL, Postman, or Insomnia</strong> to interact directly with the API endpoint and confirm its exact behavior.</p><p>This lets you understand the <strong>body, credentials, and authentication</strong> <em>before</em> you write your application code and spend hours debugging.</p><h3>Step 2: Understand the requirements (and expect the unexpected)</h3><p>When testing, focus on getting the details right for all parts of the request:</p><h4><strong>Request Body/Parameters</strong></h4><p>Figure out the required <strong>data format</strong> (JSON, form-data, etc.) and the necessary <strong>fields</strong> the API expects.</p><h4><strong>Credentials/Authentication</strong></h4><p>Determine the method of authentication. This could be an <strong>API Key</strong> in a header, a <strong>Bearer Token</strong>, or basic username/password (<strong>Basic Auth</strong>). You must configure your testing tool to pass these credentials correctly.</p><h4><strong>Advanced Security: Mutual TLS (mTLS)</strong></h4><p>For high-security APIs, you might encounter mTLS. This means the server won’t just ask for your credentials; it will also require you to a specific Client Certificate and Private Key that sometimes you are also the responsable to create/get it<strong>.</strong></p><blockquote>And just like that you have one step more before starting to do the integration.</blockquote><h4><strong>Response Verification:</strong></h4><p>Once the request is sent, <strong>verify the HTTP Status Code</strong>.</p><p>Most importantly, analyze the <strong>Response Body</strong> for both <strong>successes</strong> and <strong>failures</strong>. If the API is poorly documented, this is where you uncover whether a true error is buried inside a success code, as I experienced.</p><h3>Step 3: Finally, write it. But write it good.</h3><p>Now that you have your field notes on the API’s actual behavior, its time to write the integration. The goal here is to keep the chaos of the external API from polluting your clean business logic.</p><h4>3.1. Create a dedicated Client Layer (abstraction)</h4><p>Never let the complexity of that external API to contaminate your core application code. Instead, let’s create a single point of contact: a <strong>Client Layer.</strong></p><p>This “translator” has three simple, but crucial, jobs:</p><ol><li><strong>Build the Request:</strong> It figures out the exact headers, body, and URL the external API needs.</li><li><strong>Make the Call:</strong> It handles the raw HTTP request and gets the messy response back.</li><li><strong>Translate the Response:</strong> This is the most important part. It takes the raw, messy external data and converts it into a clean, predictable data format that your internal application can easily understand and use.</li></ol><pre>// Example within the dedicated client/repository layer<br><br>async function fetchData(data) {<br>    const response = await fetch(API_URL, { /* ... request details ... */ });<br>    const json = await response.json();<br><br>    // Check for the bizarre nested error discovered in Step 2<br>    if (response.status === 200 &amp;&amp; json.status === &#39;error&#39; &amp;&amp; json.code === 404) {<br>        throw new ResourceNotFoundException(&#39;The external resource was not found.&#39;);<br>    }<br><br>    // Check for standard HTTP errors<br>    if (!response.ok) {<br>        throw new ExternalAPIException(`API failed with status ${response.status}`);<br>    }<br><br>    // Map the messy external data structure to a clean internal object<br>    return {<br>        id: json.response.id_key,<br>        name: json.response.data.user_name_alias,<br>        // ... and so on<br>    };<br>}</pre><h4>3.2. Custom error handling</h4><p>This is where you customise the strange findings from Step 2.</p><p>If the API returns a 200 with an internal 404 status in the JSON body, your client layer must catch this and convert it into a erro.</p><h4>3.3. Timeouts and retries</h4><p>External APIs are inherently unreliable. To prevent them from crippling your entire application:</p><ul><li><strong>Timeouts:</strong> Always configure a reasonable timeout (5–10 seconds). If the API takes too long, abort the request and fail fast.</li><li><strong>Retries:</strong> If a request fails due to a temporary network glitch or server load, retrying it. Just be sure to only retry on transient errors (like 429 Too Many Requests or 5xx server errors), not permanent ones (like 400 Bad Request).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nzjIBuqx_SEKIRHW" /><figcaption>Photo by <a href="https://unsplash.com/@mnelen?utm_source=medium&amp;utm_medium=referral">Anastasiia Nelen</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Conclusion: Prevent yourself and gets more time for the coffee on twitter</h3><p>You have now got the blueprint for turning a 3-week debugging nightmare into a predictable, three-day feature win. The key takeaway from these three steps is simple: <strong>assume nothing, and protect your house.</strong></p><p><strong>But before, let me know: what is the strangest API quirk you have ever had to handle?</strong></p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ceccaa6244f" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/how-to-code-efficiently-external-apis-integration-9ceccaa6244f">How to Code Efficiently: External APIs Integration</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[API Basics: From RESTful Diners to SOAP’s Formal Galas]]></title>
            <link>https://javascript.plainenglish.io/api-basics-from-restful-diners-to-soaps-formal-galas-94ad27492224?source=rss-e61f06fa3b81------2</link>
            <guid isPermaLink="false">https://medium.com/p/94ad27492224</guid>
            <category><![CDATA[open-api]]></category>
            <category><![CDATA[soap]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[webhooks]]></category>
            <dc:creator><![CDATA[Maria Ferreira]]></dc:creator>
            <pubDate>Fri, 29 Aug 2025 09:51:54 GMT</pubDate>
            <atom:updated>2025-08-30T01:18:52.830Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve ever worked with system integrations, you’ve probably heard terms like <em>API</em>, <em>Webhook</em>, <em>OpenAPI</em>, and <em>SOAP</em>.<br> They often appear in the same conversations, but they don’t mean the same thing.</p><p>Let’s break them down in simple terms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*I-wQT8rxucPNsf0_" /><figcaption>Photo by <a href="https://unsplash.com/@introspectivedsgn?utm_source=medium&amp;utm_medium=referral">Erik Mclean</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>REST API and OpenAPI</h3><h4><strong>REST</strong> (Representational State Transfer)</h4><p>Is a popular, flexible architectural style for designing APIs. It’s designed to be simple and easy to use, leveraging standard HTTP methods like GET, POST, PUT, and DELETE to perform operations on resources.</p><p>Resources can be anything, such as a user, a product, or a blog post. Data is typically sent and received in <strong>JSON</strong> (JavaScript Object Notation) format, which is lightweight and human-readable.</p><p><strong>REST API Example:</strong> Let’s say you’re building a simple blog application. You might interact with the blog’s API like this:</p><pre>POST /posts HTTP/1.1<br>Host: api.example.com<br>Content-Type: application/json<br>Authorization: Bearer YOUR_ACCESS_TOKEN<br><br>{<br>  &quot;title&quot;: &quot;My New Post Title&quot;,<br>  &quot;content&quot;: &quot;This is the amazing content for my new blog post.&quot;<br>}</pre><p>This request retrieves a list of all blog posts. The API responds with a JSON array of post objects, a response like:</p><pre>201 Created<br>Content-Type: application/json<br><br>{<br>  &quot;id&quot;: 4,<br>  &quot;title&quot;: &quot;My New Post Title&quot;<br>}</pre><h4><strong>OpenAPI</strong></h4><p>Is a <strong>specification</strong> used to describe and document REST APIs. It defines all the available endpoints, the data they accept, and the responses they return. Tools can use this file to automatically generate documentation, client libraries, or even server code. It ensures that everyone working on the API is on the same page. The file is typically in <strong>YAML</strong> or <strong>JSON</strong> format.</p><p><strong>OpenAPI Example (YAML):</strong></p><pre>openapi: 3.0.0<br>info:<br>  title: Simple Blog API<br>  version: 1.0.0<br>paths:<br>  /posts:<br>    get:<br>      summary: Get all blog posts<br>      responses:<br>        &#39;200&#39;:<br>          description: A list of posts<br>          content:<br>            application/json:<br>              schema:<br>                type: array<br>                items:<br>                  type: object<br>                  properties:<br>                    id:<br>                      type: integer<br>                    title:<br>                      type: string<br>    post:<br>      summary: Create a new post<br>      requestBody:<br>        required: true<br>        content:<br>          application/json:<br>            schema:<br>              type: object<br>              properties:<br>                title:<br>                  type: string<br>                content:<br>                  type: string</pre><h3>SOAP and WSDL</h3><h4>SOAP</h4><p>Think of SOAP as a very strict, formal way of building APIs. It emerged in the early 2000s, it is based on XML, and usually comes with a <strong>WSDL (Web Services Description Language)</strong> file, which describes:</p><ul><li>Available methods (e.g., ListProjects, AddClient).</li><li>Parameters each method accepts.</li><li>The expected response format.</li><li>Strongly tied to enterprise standards like <strong>WS-Security</strong> and <strong>WS-Policy</strong>.</li><li>Still widely used in <strong>banks, ERPs, and government systems</strong>.</li></ul><p><strong>SOAP Request Example:</strong> Let’s say you’re interacting with a financial system to check a client’s account balance.</p><pre>&lt;soapenv:Envelope xmlns:soapenv=&quot;http://schemas.xmlsoap.org/soap/envelope/&quot; xmlns:acc=&quot;http://example.com/account&quot;&gt;<br>   &lt;soapenv:Header/&gt;<br>   &lt;soapenv:Body&gt;<br>      &lt;acc:GetBalance&gt;<br>         &lt;acc:clientId&gt;12345&lt;/acc:clientId&gt;<br>      &lt;/acc:GetBalance&gt;<br>   &lt;/soapenv:Body&gt;<br>&lt;/soapenv:Envelope&gt;</pre><h4><strong>WSDL</strong> (Web Services Description Language)</h4><p>An XML-based language used to describe what a SOAP web service can do. It’s like the instruction manual for the SOAP API. It specifies the available operations (functions), the parameters they require, and the data structures for requests and responses. A WSDL file is required for a client to know how to properly format a SOAP request.</p><pre>&lt;wsdl:definitions xmlns:wsdl=&quot;http://schemas.xmlsoap.org/wsdl/&quot; xmlns:xsd=&quot;http://www.w3.org/2001/XMLSchema&quot; targetNamespace=&quot;http://example.com/account&quot;&gt;<br>  &lt;wsdl:types&gt;<br>    &lt;xsd:schema targetNamespace=&quot;http://example.com/account&quot;&gt;<br>      &lt;xsd:element name=&quot;GetBalance&quot;&gt;<br>        &lt;xsd:complexType&gt;<br>          &lt;xsd:sequence&gt;<br>            &lt;xsd:element name=&quot;clientId&quot; type=&quot;xsd:string&quot;/&gt;<br>          &lt;/xsd:sequence&gt;<br>        &lt;/xsd:complexType&gt;<br>      &lt;/xsd:element&gt;<br>      &lt;xsd:element name=&quot;GetBalanceResponse&quot;&gt;<br>        &lt;xsd:complexType&gt;<br>          &lt;xsd:sequence&gt;<br>            &lt;xsd:element name=&quot;balance&quot; type=&quot;xsd:decimal&quot;/&gt;<br>          &lt;/xsd:sequence&gt;<br>        &lt;/xsd:complexType&gt;<br>      &lt;/xsd:element&gt;<br>    &lt;/xsd:schema&gt;<br>  &lt;/wsdl:types&gt;<br>  &lt;wsdl:message name=&quot;GetBalanceRequestMessage&quot;&gt;<br>    &lt;wsdl:part name=&quot;parameters&quot; element=&quot;tns:GetBalance&quot;/&gt;<br>  &lt;/wsdl:message&gt;<br>  &lt;/wsdl:definitions&gt;</pre><h3>Webhook</h3><p>While APIs let you <em>request</em> data, a <strong>Webhook</strong> lets systems <em>push</em> data to you automatically.</p><ul><li>Works like a “reverse API call.”</li><li>You give the source system a URL, and whenever an event happens, it sends an HTTP request to that URL.</li><li>Example: A payment gateway sends a POST request to your system when a transaction is completed.</li></ul><p>👉 Ideal for <strong>real-time notifications</strong> without constantly polling an API.</p><h3>Mapping the concepts</h3><p>To make it crystal clear:</p><ul><li><strong>SOAP ↔ REST</strong> → Two different approaches for building APIs.</li><li><strong>WSDL ↔ OpenAPI</strong> → Specifications for describing those APIs.</li><li><strong>Webhook</strong> → A mechanism for real-time event-driven communication.</li></ul><h3>Putting It All Together</h3><p>Think of it this way: <strong>REST</strong> and <strong>SOAP</strong> are like two different restaurants. REST is a modern, fast-casual diner with a simple menu (<strong>JSON</strong>) that’s easy to read and order from. The <strong>OpenAPI</strong> spec is the menu and a floor plan for this diner, telling you exactly what’s available and how to get it.</p><p><strong>SOAP</strong>, on the other hand, is a formal, old-world gala. Everything follows a strict, well-defined etiquette (<strong>XML</strong>). The <strong>WSDL</strong> file is the formal invitation and program for the evening, detailing every step of the ceremony, from the arrival to the final toast.</p><p><strong>Webhooks</strong> are a different kind of communication entirely. They’re not about you ordering from a menu; they’re like getting a text message from the valet to let you know your car is ready. They provide an immediate, event-driven notification, which is perfect for real-time updates without the need for constant checking.</p><p>Thanks for reading :)</p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94ad27492224" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/api-basics-from-restful-diners-to-soaps-formal-galas-94ad27492224">API Basics: From RESTful Diners to SOAP’s Formal Galas</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Async JavaScript: Callbacks, Promises and Async/Await Explained]]></title>
            <link>https://javascript.plainenglish.io/async-javascript-callbacks-promises-and-async-await-explained-e57b9b4f6677?source=rss-e61f06fa3b81------2</link>
            <guid isPermaLink="false">https://medium.com/p/e57b9b4f6677</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[asynchronous-programming]]></category>
            <category><![CDATA[https]]></category>
            <dc:creator><![CDATA[Maria Ferreira]]></dc:creator>
            <pubDate>Mon, 28 Jul 2025 13:01:05 GMT</pubDate>
            <atom:updated>2025-07-29T00:42:53.896Z</atom:updated>
            <content:encoded><![CDATA[<p>JavaScript’s asynchronous nature is both a blessing and a curse.</p><p>Callbacks used to be the standard, but they came with headaches. Then came <strong>Promises</strong>, and later <strong>async/await</strong>, making async code more readable, predictable, and scalable. With modern APIs like fetch and tools like axios, async logic has never been more elegant.</p><p>Let’s break it all down.</p><h3>A Brief History</h3><h4>📌 Callbacks (Pre-ES6, before 2015)</h4><p>In early JavaScript (Node.js, jQuery era), the primary way to handle asynchronous code was through <strong>callbacks</strong> — <strong>functions passed as arguments that are called when a task completes</strong>.</p><h4>📌 Promises (ES6, 2015)</h4><p>ES6 introduced <strong>Promises</strong> to solve this. A Promise represents a <strong>value that may be available now, later, or never</strong>, and allows clean <strong>chaining</strong>, <strong>error handling</strong>, and <strong>composability</strong>.</p><h4>📌 A<strong>sync/await</strong> (ES, 2017)</h4><p>Later, <strong>async/await</strong> was introduced in <strong>ES2017</strong>, providing a more synchronous-looking way to write asynchronous code — built on top of Promises.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mY5ji0ceKcm1W5CP" /><figcaption>Photo by <a href="https://unsplash.com/@growtika?utm_source=medium&amp;utm_medium=referral">Growtika</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>The Problem with Callbacks (Pre-ES6, before 2015)</h3><p>Let’s say you want to:</p><ol><li>Fetch a user from a database</li><li>Get their posts</li><li>Display those posts</li></ol><pre>function getUser(id, callback) {<br>  setTimeout(() =&gt; {<br>    callback(null, { id, name: &#39;Alice&#39; });<br>  }, 1000); // setTimeout for simulate network/database delay<br>}<br><br>function getPosts(userId, callback) {<br>  setTimeout(() =&gt; {<br>    callback(null, [`Post 1`, `Post 2`]);<br>  }, 1000);<br>}<br><br>// Usage<br>getUser(1, (err, user) =&gt; {<br>  if (err) return console.error(&#39;User error:&#39;, err);<br><br>  getPosts(user.id, (err, posts) =&gt; {<br>    if (err) return console.error(&#39;Post error:&#39;, err);<br><br>    console.log(&#39;Posts:&#39;, posts);<br>  });<br>});</pre><h4>Issues:</h4><ul><li><strong>Nested callbacks</strong> = difficult to read and maintain</li><li><strong>Inconsistent error handling</strong></li><li>Harder to reuse, compose, or manage multiple async tasks</li></ul><h4>Why setTimeout?</h4><p>We are not using setTimeout for delays — we are using it to simulate asynchronous behavior. In real-world apps, fetching data from a database or API is not instant.</p><p>setTimeout is a common technique in learning, testing, and mocking to imitate async operations without needing an actual server or API.</p><h3>The solution using Promises (ES6, 2015)</h3><p>With Promises, you return an object that represents the result of an async operation. You can <strong>chain </strong><strong>.then()</strong> for success and <strong>.catch()</strong> for errors.</p><pre>function getUser(id) {<br>  return new Promise((resolve, reject) =&gt; {<br>    setTimeout(() =&gt; {<br>      resolve({ id, name: &#39;Alice&#39; });<br>    }, 1000); // setTimeout for simulate network/database delay<br>  });<br>}<br><br>function getPosts(userId) {<br>  return new Promise((resolve, reject) =&gt; {<br>    setTimeout(() =&gt; {<br>      resolve([`Post 1`, `Post 2`]);<br>    }, 1000);<br>  });<br>}<br><br>// Usage<br>getUser(1)<br>  .then((user) =&gt; getPosts(user.id))<br>  .then((posts) =&gt; console.log(&#39;Posts:&#39;, posts))<br>  .catch((err) =&gt; console.error(&#39;Error:&#39;, err));</pre><h4>Benefits:</h4><ul><li>Flat and readable structure</li><li>Centralized error handling with .catch()</li><li>Easier to compose with Promise.all, Promise.race, etc.</li></ul><h3>Even Cleaner with Async/Await (ES2017)</h3><p>Async/await makes your asynchronous code look like synchronous code. It is just syntactic sugar over Promises — but it is sweet haha</p><pre>async function showUserPosts() {<br>  try {<br>    const user = await getUser(1);<br>    const posts = await getPosts(user.id);<br>    console.log(&#39;Posts:&#39;, posts);<br>  } catch (err) {<br>    console.error(&#39;Error:&#39;, err);<br>  }<br>}<br><br>showUserPosts();</pre><h4>Cleaner, right?</h4><ul><li>No .then() chaining</li><li>Easier to debug</li><li>More expressive and modern</li></ul><h3>Real-World APIs: fetch and axios</h3><p>Let’s replace our fake async functions using setTimeout with real HTTP calls using fetch and axios.</p><h4>Using fetch (native, browser built-in)</h4><pre>async function getUser(id) {<br>  const response = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`);<br>  if (!response.ok) throw new Error(&#39;Network response was not ok&#39;);<br>  return response.json();<br>}<br><br>async function getPosts(userId) {<br>  const response = await fetch(`https://jsonplaceholder.typicode.com/posts?userId=${userId}`);<br>  if (!response.ok) throw new Error(&#39;Failed to fetch posts&#39;);<br>  return response.json();<br>}</pre><ul><li>Built-in: Yes (modern browsers)</li><li>JSON handling: Manual (res.json())</li><li>Request config: Limited</li><li>Error handling: Must check .ok manually</li><li>Node.js support: Needs node-fetch</li><li>Upload/download: Basic</li></ul><h4>Using axios (more powerful, popular)</h4><pre>npm install axios</pre><pre>import axios from &#39;axios&#39;;<br><br>async function getUser(id) {<br>  const response = await axios.get(`https://jsonplaceholder.typicode.com/users/${id}`);<br>  return response.data;<br>}<br><br>async function getPosts(userId) {<br>  const response = await axios.get(`https://jsonplaceholder.typicode.com/posts`, {<br>    params: { userId }<br>  });<br>  return response.data;<br>}</pre><ul><li>Built-in: No (needs install)</li><li>JSON handling: Automatic</li><li>Request config: Full support (headers, params, timeouts)</li><li>Error handling: Rejects on HTTP errors</li><li>Node.js support: Out of the box</li><li>Upload/download: Better support</li></ul><h4>Using either in practice:</h4><pre>async function showUserPosts() {<br>  try {<br>    const user = await getUser(1);<br>    const posts = await getPosts(user.id);<br>    console.log(&#39;Posts:&#39;, posts.map(post =&gt; post.title));<br>  } catch (err) {<br>    console.error(&#39;Error:&#39;, err.message);<br>  }<br>}</pre><h3>Bonus: Promise methods that level up async logic</h3><p>Beyond just .then() and .catch(), Promises include several built-in <strong>static methods</strong> that make handling complex async flows easier:</p><h4>1. Promise.resolve(value)</h4><p>Creates a promise that immediately resolves with the given value.</p><pre>Promise.resolve(42).then(console.log); // Logs: 42</pre><p>Useful for testing, stubbing, or adapting synchronous values to async flows.</p><h4>2. Promise.reject(error)</h4><p>Creates a promise that immediately rejects:</p><pre>Promise.reject(new Error(&#39;Oops&#39;)).catch(console.error);</pre><p>Good for simulating error conditions.</p><h4>3. Promise.all ([...])</h4><p>Runs multiple promises <strong>in parallel</strong> and <strong>waits for all</strong> to succeed. If one fails, the whole thing fails.</p><pre>Promise.all([getUser(1), getPosts(1)])<br>  .then(([user, posts]) =&gt; {<br>    console.log(user, posts);<br>  })<br>  .catch(console.error);</pre><p>Perfect for tasks that can happen at the same time — like fetching different endpoints.</p><h4>4. Promise.race([...])</h4><p>Runs multiple promises and returns the result of the <strong>first one to finish</strong>, whether it resolves or rejects.</p><pre>Promise.race([<br>  fetch(&#39;/fast-endpoint&#39;),<br>  fetch(&#39;/slow-endpoint&#39;),<br>])<br>  .then((response) =&gt; console.log(&#39;Fastest won:&#39;, response))<br>  .catch(console.error);</pre><p>Useful for <strong>timeouts</strong>, <strong>fallbacks</strong>, or load balancing.</p><h4>5. Promise.allSettled([...]) (ES2020)</h4><p>Waits for all promises to complete, <strong>regardless of whether they succeed or fail</strong>.</p><pre>Promise.allSettled([<br>  fetch(&#39;/data1&#39;),<br>  fetch(&#39;/data2&#39;),<br>])<br>.then((results) =&gt; {<br>  results.forEach(result =&gt; {<br>    if (result.status === &#39;fulfilled&#39;) {<br>      console.log(&#39;Success:&#39;, result.value);<br>    } else {<br>      console.error(&#39;Error:&#39;, result.reason);<br>    }<br>  });<br>});</pre><p>Great for showing partial results or aggregating errors.</p><h3>Conclusion</h3><p>JavaScript’s async story has come a long way:</p><ul><li>From callback pyramids…</li><li>To promise chains…</li><li>To elegant async/await syntax.</li><li>And now, powerful tools like axios and fetch simplify HTTP communication.</li></ul><blockquote>fetch<strong><em> is great for simple things. </em></strong>axios<strong><em> shines when things get complex.</em></strong><em><br> And with Promises, async JavaScript is finally powerful, flexible, and maintainable.</em></blockquote><p>Goodbye callback hell.<br>Hello async elegance. 💅🏽</p><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏️<strong>️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/@InPlainEnglish"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a> | <a href="https://twitch.tv/inplainenglish"><strong>Twitch</strong></a></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e57b9b4f6677" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/async-javascript-callbacks-promises-and-async-await-explained-e57b9b4f6677">Async JavaScript: Callbacks, Promises and Async/Await Explained</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TDD — What it is and how you actually use it]]></title>
            <link>https://medium.com/@mariaferreira.developer/tdd-what-it-is-and-how-you-actually-use-it-e8eac6b9a0b4?source=rss-e61f06fa3b81------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8eac6b9a0b4</guid>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[test-driven-development]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[best-practices]]></category>
            <dc:creator><![CDATA[Maria Ferreira]]></dc:creator>
            <pubDate>Fri, 25 Jul 2025 14:12:55 GMT</pubDate>
            <atom:updated>2025-07-25T14:12:55.553Z</atom:updated>
            <content:encoded><![CDATA[<h3>TDD — What it is and how you actually use it</h3><p><strong>Test-Driven Development (TDD)</strong> is a software development approach where you write tests <strong><em>before</em></strong> writing the actual code. The idea is to define how your code should behave upfront and then build the code to pass those tests.</p><h3>Why TDD?</h3><ul><li>Ensures your code meets requirements</li><li>Helps catch bugs early</li><li>Encourages simple, modular, and testable code</li><li>Improves confidence in refactoring and extending code</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pUyEzapco4YvjWaw" /><figcaption>Photo by <a href="https://unsplash.com/@stepan_konev?utm_source=medium&amp;utm_medium=referral">Stepan Konev</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Red → Green → Refactor</h3><p>TDD follows a simple cycle called <strong>Red-Green-Refactor</strong>:</p><ol><li><strong>Red:</strong> Write a test for a new feature or behavior. Since the code doesn’t exist yet, the test will fail (red).</li><li><strong>Green:</strong> Write just enough code to make the test pass. Keep it simple!</li><li><strong>Refactor:</strong> Clean up the code while making sure the tests still pass. Remove duplication and improve design.</li></ol><p>Repeat this cycle for every small piece of functionality.</p><h3>Example (JavaScript)</h3><pre>// Step 1: Write a failing test (Red)<br>test(&#39;adds two numbers&#39;, () =&gt; {<br>  expect(add(2, 3)).toBe(5);<br>});<br><br>// Step 2: Write minimal code to pass the test (Green)<br>function add(a, b) {<br>  return a + b;<br>}<br><br>// Step 3: Refactor if needed (Refactor)</pre><h3>Why even bother with this?</h3><p>Let’s be honest — sometimes writing tests feels like extra work. But once you get used to it, you realize:</p><ul><li>You build <strong>only what you need</strong></li><li>You stop shipping things that accidentally break something else</li><li>You refactor code <strong>without fear</strong></li><li>And tests become your <strong>documentation</strong> for how things are <em>supposed</em> to work</li></ul><p>Basically, it saves your future self from pain.</p><h3>What do you actually test?</h3><p>You don’t need to go wild and test <em>everything</em>. TDD isn’t about coverage bragging. Focus on:</p><ul><li>Core logic</li><li>Critical flows</li><li>Edge cases (null, empty, negative, etc.)</li><li>Reusable functions or utilities</li></ul><p>Don’t worry about testing private functions, animations, or that a button has rounded corners. Test <strong>behavior</strong>.</p><h3>What tools do I need?</h3><p>It depends on your stack. Most frameworks already have solid tools:</p><ul><li><strong>JavaScript/TypeScript</strong>: Jest, Mocha</li><li><strong>Python</strong>: unittest, pytest</li><li><strong>Java</strong>: JUnit</li><li><strong>React</strong>: React Testing Library</li><li><strong>Node</strong>: supertest (for HTTP testing)</li><li><strong>Backend APIs</strong>: Postman + Newman, or just integration/unit tests</li></ul><h3>Okay, but how do I TDD a real feature?</h3><p>Let’s say you’re building a getUserGreeting() function:</p><h4>1. Write the test:</h4><pre>test(&#39;greets user by name&#39;, () =&gt; {<br>  expect(getUserGreeting(&#39;Alice&#39;)).toBe(&#39;Hello, Alice!&#39;);<br>});</pre><h4>2. Write the function:</h4><pre>function getUserGreeting(name) {<br>  return `Hello, ${name}!`;<br>}</pre><p>Passes? ✅ Cool.</p><p>Now imagine you expand it to handle empty names, or customize language.<br> Each new behavior → new test → minimal code → refactor.</p><p>You’re building your logic like LEGO blocks, with confidence.</p><h3>Conclusion</h3><p>TDD isn’t a silver bullet, but it’s one of those habits that pays off fast if you stick with it.</p><p>You start coding with more <strong>intention</strong>.<br>You stop pushing broken stuff.<br>You spend less time debugging and more time <strong>shipping</strong>.</p><p>If you have avoided it because it felt like too much, try it out on one small function in your next project.</p><p>No need to go full “Uncle Bob”. Just get the basics working for <em>you</em>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8eac6b9a0b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SOLID — Explaining Each Principle and How It Applies in Practice]]></title>
            <link>https://medium.com/@mariaferreira.developer/solid-explaining-each-principle-and-how-it-applies-in-practice-f0ff499f634a?source=rss-e61f06fa3b81------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0ff499f634a</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[solid-principles]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Maria Ferreira]]></dc:creator>
            <pubDate>Wed, 23 Jul 2025 21:18:07 GMT</pubDate>
            <atom:updated>2025-07-23T21:18:07.859Z</atom:updated>
            <content:encoded><![CDATA[<h3>SOLID — Explaining Each Principle and How It Applies in Practice</h3><p>Understanding <strong>SOLID principles</strong> is about to writing clean, maintainable, and scalable object-oriented software. Introduced by <strong>Robert C. Martin (Uncle Bob)</strong>, to help developers manage software complexity and create systems that are easy to refactor, extend, and test.</p><h3>SOLID</h3><p>SOLID is an acronym, and each letter represents a crucial principle. Let’s break down each principle and see how it applies in real-world development.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5bsZEeQ7FhzCVMX4" /><figcaption>Photo by <a href="https://unsplash.com/@googledeepmind?utm_source=medium&amp;utm_medium=referral">Google DeepMind</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>S — Single Responsibility Principle (SRP)</h3><p>A <strong>class</strong> should have <strong>only one</strong> reason to exist.</p><h4>What it means:</h4><p>Each class or module should <strong>only have one <em>responsibility</em></strong>, and do it well. This makes your code easier to read, test, and maintain.</p><h4><strong>Example</strong>:</h4><p>Instead of:</p><pre>class ReportManager {<br><br>  generateReport() { ... } //   Generate report method<br><br>  saveToFile() { ... } // Save report method<br>}</pre><p>Separate responsibilities:</p><pre>class ReportGenerator { // Separate classes, for different responsibility.<br>  generate() { ... }<br>}<br><br>class ReportSaver { // Separate classes, for different responsibility.<br>  saveToFile() { ... }<br>}</pre><p><strong>Why it matters</strong>:<br>If both generateReport() and saveToFile() are part of the same class and something breaks inside saveToFile() — for example, a file permission error, disk issue, or unexpected input — it can cause instability in the entire ReportManager class.</p><p>That means <strong>even logic that has nothing to do with saving (like generating the report)</strong> could be harder to use, test, or debug, simply because it shares the same class.</p><h3>O — Open/Closed Principle (OCP)</h3><p>Software entities should be <strong>open for extension</strong>, but <strong>closed for modification</strong>.</p><p><strong>In practice</strong>:<br>You should be able to <strong>add new features without changing existing code</strong> — a key to making your codebase robust and flexible.</p><h4><strong>Example</strong>:</h4><p>Instead of:</p><pre>function calculateDiscount(userType) {<br>  if (userType === &#39;premium&#39;) return 0.2;<br>  if (userType === &#39;standard&#39;) return 0.1;<br>}</pre><p>Use polymorphism:</p><pre>class DiscountStrategy {<br>  // This method provides a default discount (0 in this case)<br>  getDiscount() {<br>    return 0;<br>  }<br>}<br><br>// Subclass that extends DiscountStrategy (base class)<br>class PremiumUser extends DiscountStrategy {<br>  getDiscount() { // Overrides the method to return a smaller discount<br>    return 0.2; // 20% discount<br>  }<br>}<br><br>// Same here<br>class StandardUser extends DiscountStrategy {<br>  getDiscount() { <br>    return 0.1; // 10% discount<br>  }<br>}</pre><h4>What is happening:</h4><ol><li>DiscountStrategy acts as a <strong>base class</strong> or <strong>interface</strong> — it defines a general contract for how discounts should be calculated.</li><li>PremiumUser and StandardUser are <strong>child classes</strong> that <strong>override</strong> the getDiscount() method with their own logic.</li><li>Anywhere in your code, you can work with instances of DiscountStrategy without caring which exact subclass it is — that’s <strong>polymorphism</strong>.</li></ol><h4>Example usage:</h4><pre>function printUserDiscount(user) {<br>  console.log(`User discount: ${user.getDiscount() * 100}%`);<br>}<br><br>const premium = new PremiumUser();<br>const standard = new StandardUser();<br>printUserDiscount(premium);   // Output: User discount: 20%<br>printUserDiscount(standard);  // Output: User discount: 10%</pre><p>In this example, both premium and standard are used interchangeably via the same getDiscount() method — this is the power of <strong>polymorphism</strong> in action.</p><h3>L — Liskov Substitution Principle (LSP)</h3><p>Objects (an instance of a class) of a superclass (a class extended by others) should be <strong>replaceable</strong> with objects of a subclass without breaking the app.</p><h4><strong>In practice</strong>:</h4><p>Subclasses should <strong>preserve the behavior</strong> of the base class. Violating this leads to bugs.</p><h4><strong>Example</strong> (violation):</h4><pre>class File { // Superclass<br>  open() {<br>    console.log(&quot;Opening file...&quot;);<br>  }<br><br>  read() {<br>    console.log(&quot;Reading data from file...&quot;);<br>  }<br><br>  write() {<br>    console.log(&quot;Writing data...&quot;);<br>  }<br>}<br><br>class WriteOnlyFile extends File { // Subclass <br>  read() {<br>    throw new Error(&quot;Cannot read from a write-only file&quot;);<br>  }<br>}</pre><p>Where the bug appears:</p><pre>function handleFile(file) {<br>  file.open();<br>  file.read(); // This may throw if it&#39;s a WriteOnlyFile<br>}<br><br>const f = new WriteOnlyFile();<br>handleFile(f); // 💥 App crashes</pre><h4>Example good practice (Respecting LSP):</h4><pre>class File {<br>  open() {<br>    console.log(&quot;Opening file...&quot;);<br>  }<br>}<br><br>class ReadableFile extends File {<br>  read() {<br>    console.log(&quot;Reading from file...&quot;);<br>  }<br>}<br><br>class WriteOnlyFile extends File {<br>  write(data) {<br>    console.log(`Writing &quot;${data}&quot; to file...`);<br>  }<br>}</pre><p>Now only ReadableFile has the read() method, and your logic can treat files based on their actual abilities.</p><pre>function handleFile(file) {<br>  file.open();<br>  if (file instanceof ReadableFile) {<br>    file.read();<br>  } else {<br>    console.log(&quot;This file is not readable.&quot;);<br>  }<br>}</pre><h4><strong>Why it matters</strong>:</h4><p>When you create a base class (superclass) and put methods into it, <strong>all subclasses inherit those methods</strong> — whether they make sense for them or not.</p><p>The secret is: only include methods in a class if <strong>every subclass can logically use them</strong> without throwing errors or ignoring them.</p><p>If not, <strong>restructure your class hierarchy</strong> or <strong>split behaviors</strong> into interfaces or separate abstract classes.</p><h3>I — Interface Segregation Principle (ISP)</h3><p>Any class, module, or component that uses an interface should <strong>not be forced to depend on interfaces they do not use</strong>.</p><blockquote><em>💡An </em><strong><em>interface</em></strong><em> defines </em><strong><em>what methods or properties a class should have</em></strong><em> — without specifying </em><strong><em>how</em></strong><em> they should work.</em></blockquote><p><strong>In practice</strong>:<br>Design <strong>smaller, focused interfaces</strong>, rather than one large all-in-one contract.</p><h4><strong>Example</strong> (violation):</h4><pre>interface Machine {<br>  print(): void;<br>  scan(): void;<br>  fax(): void;<br>}<br><br>class OldPrinter implements Machine {<br>  print() { console.log(&quot;Printing...&quot;); }<br>  scan() { throw new Error(&quot;Scan not supported&quot;); }<br>  fax() { throw new Error(&quot;Fax not supported&quot;); }<br>}</pre><p>Here, OldPrinter is a <strong>client</strong> of the Machine interface. But it <strong>doesn&#39;t need</strong> scan() or fax() — yet it is <strong>forced to implement them</strong>. Basically the same then Liskov Substitution Principle, but instead of the methods, you need to pay attention on the interfaces.</p><h4>Example using Interface Segregation Principle:</h4><pre>interface Printable {<br>  print(): void;<br>}<br><br>interface Scannable {<br>  scan(): void;<br>}<br><br>interface Faxable {<br>  fax(): void;<br>}<br><br>class OldPrinter implements Printable {<br>  print() { console.log(&quot;Printing...&quot;); }<br>}</pre><p><strong>Why it matters</strong>:<br>When a class is forced to implement methods it doesn’t need, your code becomes:</p><ul><li><strong>Bloated</strong> — You end up with empty or fake implementations (throw new Error(...)), which add noise.</li><li><strong>Fragile</strong> — Changes to unused methods in an interface can break unrelated classes.</li><li><strong>Harder to understand</strong> — Developers have to mentally filter out irrelevant methods.</li></ul><h3>D — Dependency Inversion Principle (DIP)</h3><p><strong>Definition</strong>:<br>The core logic of your app should not be connected directly to specific tools (like JwtAuthentication, for example) or services. Instead, they should both <strong>use a general structure</strong> (like an interface) so you can swap things out easily.</p><p><strong>In practice</strong>:<br>You should <strong>depend on interfaces</strong>, not specific implementations.</p><p><strong>Example</strong>:<br>Instead of:</p><pre>class EmailService {<br>  send(email) {<br>    console.log(&quot;Sending email:&quot;, email);<br>  }<br>}<br><br>class NotificationManager {<br>  private emailService;<br><br>  constructor() {<br>    // Direct dependency on EmailService — tightly coupled<br>    this.emailService = new EmailService();<br>  }<br><br>  notify(email) {<br>    this.emailService.send(email);<br>  }<br>}</pre><h4>What’s wrong here?</h4><ul><li>NotificationManager is <strong>directly tied</strong> to EmailService.</li><li>You <strong>can’t reuse</strong> it with another service (like SMS or Push).</li><li>It’s <strong>harder to test</strong>, since you can’t easily replace EmailService with a mock or fake.</li></ul><h4>Example using dependency injection:</h4><pre>// Abstraction (interface)<br>class IMessageService {<br>  send(email) {<br>    throw new Error(&quot;Not implemented&quot;);<br>  }<br>}<br><br>// Concrete implementation<br>class EmailService extends IMessageService {<br>  send(email) {<br>    console.log(&quot;Sending email:&quot;, email);<br>  }<br>}<br><br>class NotificationManager {<br>  private messageService;<br><br>  constructor(messageService) {<br>    // Now we depend on the abstraction, not the concrete class<br>    this.messageService = messageService;<br>  }<br><br>  notify(email) {<br>    this.messageService.send(email);<br>  }<br>}</pre><p>Now you can inject <strong>any message service</strong>:</p><pre>const emailService = new EmailService();<br>const manager = new NotificationManager(emailService);<br>manager.notify(&quot;hello@world.com&quot;);</pre><p>Now, NotificationManager can work with any service that follows the expected interface.</p><h4><strong>Why it matters</strong>:</h4><ul><li><strong>Swappable dependencies</strong> — easily switch between Email, SMS, Push, etc.</li><li><strong>Easier to test</strong> — inject fakes or mocks for unit testing.</li><li><strong>Looser coupling</strong> — changes in one class don’t break others.</li><li><strong>More flexible architecture</strong> — cleaner, more modular systems.</li></ul><h3>Conclusion</h3><p>The <strong>SOLID principles</strong> are not just theory — they help you write code that is:</p><ul><li><strong>Easier to test</strong></li><li><strong>Faster to refactor</strong></li><li><strong>Simpler to extend</strong></li><li><strong>More stable in the long run</strong></li></ul><p>Whether you are building a large-scale backend service, a mobile app, or a front-end UI component, applying SOLID will elevate the quality and maintainability of your codebase.</p><h3>Quick Recap</h3><ul><li><strong>S — Single Responsibility</strong>: One class, one objetive.</li><li><strong>O — Open/Closed</strong>: Extend, don’t modify.</li><li><strong>L — Liskov Substitution</strong>: Subclasses should be replaceable and work as expected without breaking functionality.</li><li><strong>I — Interface Segregation</strong>: Small, focused interfaces. Don’t force classes to implement methods they don’t need.</li><li><strong>D — Dependency Inversion</strong>: Depend on abstractions, not concrete classes.</li></ul><p>Got questions about SOLID in real projects? Or want to see how it applies to functional programming or React? Drop a comment or reach out :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0ff499f634a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Global Error Handling in Express.js: A Complete Guide]]></title>
            <link>https://javascript.plainenglish.io/how-i-set-up-a-global-error-handler-in-express-js-and-why-you-should-too-800d80770cce?source=rss-e61f06fa3b81------2</link>
            <guid isPermaLink="false">https://medium.com/p/800d80770cce</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[logs]]></category>
            <category><![CDATA[error-handling]]></category>
            <dc:creator><![CDATA[Maria Ferreira]]></dc:creator>
            <pubDate>Wed, 16 Jul 2025 15:53:12 GMT</pubDate>
            <atom:updated>2025-07-22T11:41:32.227Z</atom:updated>
            <content:encoded><![CDATA[<p>When I first started building backend services with Express.js, I was wrapping pretty much every controller and service with a try/catch block. It felt like the responsible thing to do — I mean, <em>how else was I supposed to handle errors?</em></p><h3>The Pitfalls of “Try/Catch Everything”</h3><p>Even though I was “catching” the errors, I had <strong>no real control over them</strong>. If something crashed in production and I wasn’t watching the server logs in real time, I’d have no idea anything went wrong. Unless a user reported it, the issue would just sit there quietly, doing damage.</p><p>That was a wake-up call.</p><h3>The Solution: Global Error Handling with Middleware</h3><p>Eventually, I realized I could handle errors <em>globally</em> — with a single middleware. And not just that: I could actually <strong>log them into my database</strong> and <strong>display them in my backoffice</strong>, or even <strong>send them directly to my email</strong>.</p><p>Imagine this: instead of scattering try/catch blocks everywhere, a single, centralized error handler can intercept <em>all</em> unhandled errors across your application. And the best part? This opens up a world of possibilities for proactive error management:</p><ul><li><strong>Real-time Notifications:</strong> Immediately receive full error details (message, route, stack trace, user context, etc.) via email, Slack, or dedicated monitoring tools.</li><li><strong>Centralized Logging &amp; Analytics:</strong> Log every error into your database, allowing you to build custom dashboards, track trends, and identify recurring issues. (I even built a custom error dashboard for my admin panel to track the last 100 errors — screenshot coming soon!)</li><li><strong>Automated Remediation (Advanced):</strong> In more sophisticated setups, you could even trigger automated actions based on certain error types.</li><li><strong>Clean User Responses:</strong> Present consistent, user-friendly error messages without exposing sensitive internal details.</li></ul><p>This paradigm shift changed everything for me. No more guesswork, no more frantic log searching — just immediate, actionable intelligence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sLGuQp3ybPic69Vuk_XyIQ.png" /></figure><h3>Understanding next(err) in Express.js</h3><p>In Express, next is a special function that moves the request to the next middleware. But when you call next(err) <em>with an error</em>, you&#39;re telling Express:</p><blockquote><em>“Hey, something broke. Skip the rest of the route handlers and jump straight to the error-handling middleware.”</em></blockquote><p>This was a game-changer for me. It’s basically how Express knows to stop normal processing and switch into “error mode.”</p><h3>Normal next( ) vs next(err)</h3><ul><li>✅ next() → goes to the next middleware/route</li><li>❌ next(err) → <strong>skips everything</strong> and jumps to error handler</li></ul><h3>Example Flow: Putting It All Together</h3><p>My solution involves a catchAsync wrapper. A simple higher-order function that allows you to write asynchronous route handlers without explicitly wrapping them in try/catch. It automatically catches any errors thrown within the asynchronous function and passes them directly to next(err), ensuring they reach our global error handler.</p><p>First, here’s the catchAsync utility:</p><pre>// utils/catchAsync.js<br><br>export default function catchAsync(fn) {<br>    return function (req, res, next) {<br>      // Promise.resolve ensures that if &#39;fn&#39; returns a non-promise, it&#39;s still wrapped.<br>      // .catch(next) ensures any error from &#39;fn&#39; is passed to the next middleware (our error handler).<br>      Promise.resolve(fn(req, res, next)).catch(next);<br>    };<br>}</pre><p>Now, instead of try/catch in your controllers, you use catchAsync in your routes to wrap your asynchronous controller functions. For instance, in my route definitions, it looks like this:</p><pre>// routes/chatRoutes.js (example)<br><br>// The catchAsync ensures any errors from createChat controller are caught<br>router.post(&quot;/&quot;, protectRoute, catchAsync(createChat));</pre><p>This pattern keeps your route definitions clean and focused on their primary logic, delegating error handling to catchAsync and ultimately to our centralized error middleware.</p><h3>The Robust Global Error Handler</h3><p>The true power comes from our global error-handling middleware. This is where we centralize logging, notification, and response formatting. Importantly, I wanted to not just log errors to the console, but persist them in my database for later analysis and display in my admin panel.</p><p>To achieve this, I created an ErrorLog model (using Mongoose, for example) to store error details, and used it in a errorHandler middleware:</p><pre>// middleware/errorHandler.js<br>import ErrorLog from &quot;../models/logs.model.js&quot;; // Import my Mongoose model<br><br>const errorHandler = async (err, req, res, next) =&gt; {<br>    console.error(&#39;Global error handler caught:&#39;, err); // For immediate server visibility<br><br>    const errorDetails = {<br>        message: err.message,<br>        stack: err.stack,<br>        route: req.originalUrl,<br>        method: req.method,<br>        time: new Date(),<br>    };<br><br>    // Log error details to the console for development/debugging<br>    console.log(&quot;Error details from middleware:&quot;, JSON.stringify(errorDetails, null, 2));<br><br>    try {<br>        // Attempt to save the error details to my database<br>        await ErrorLog.create(errorDetails);<br>    } catch (dbErr) {<br>        // Log if saving to DB fails, but don&#39;t stop the main error flow<br>        console.error(&quot;Failed to save error to MongoDB:&quot;, dbErr.message);<br>    }<br><br>    // Check if headers have already been sent to avoid &quot;Can&#39;t set headers after they are sent&quot; errors<br>    if (res.headersSent) {<br>        return next(err); // Pass to default Express error handler if response already started<br>    }<br><br>    // Determine the appropriate status code and message for the client<br>    const statusCode = err.statusCode || 500; // Custom errors might have a statusCode property<br>    const message = err.message || &#39;Internal Server Error&#39;;<br><br>    // Send a generic, user-friendly error response to the client<br>    res.status(statusCode).json({ success: false, message });<br>    // Note: We don&#39;t call next() here unless we explicitly want another error handler to run.<br>};<br><br>export default errorHandler;</pre><h4>Important:</h4><p>Your error handler <strong>must</strong> have 4 arguments:</p><pre>(err, req, res, next) =&gt; { ... }</pre><p>Otherwise, Express won’t treat it as an error handler and will ignore it.</p><p>Calling next(err):</p><ul><li>Stops normal request flow</li><li>Jumps to your centralized error handler</li><li>Lets you log the error, notify teams, and send a clean response</li></ul><p>Finally, to ensure this errorHandler catches all errors dispatched by next(err) (including those from our catchAsync wrappers), it must be placed as the <em>very last</em> middleware in your index.js (or main Express app file):</p><pre>// index.js (or app.js)<br>import express from &#39;express&#39;;<br>import errorHandler from &#39;./middleware/errorHandler.js&#39;; <br><br>const app = express();<br><br>app.use(errorHandler);<br><br>const PORT = process.env.PORT || 3000;<br>app.listen(PORT, () =&gt; console.log(`Server running on port ${PORT}`));</pre><p>This setup provides an incredibly robust and observable error-handling system. Any unhandled error in an asynchronous route, thanks to catchAsync, is seamlessly passed to next(err), caught by our errorHandler, logged to our database, and then a clean, consistent response is sent to the client.</p><p>This changed my development workflow significantly! Hope it helps you as well.</p><p>Thanks for reading :)</p><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏️<strong>️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/@InPlainEnglish"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a> | <a href="https://twitch.tv/inplainenglish"><strong>Twitch</strong></a></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=800d80770cce" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/how-i-set-up-a-global-error-handler-in-express-js-and-why-you-should-too-800d80770cce">Global Error Handling in Express.js: A Complete Guide</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Built a PDF Generator with Email Sending, RabbitMQ, Dead-Letter Queues & Docker using Node.js]]></title>
            <link>https://medium.com/@mariaferreira.developer/how-i-built-a-pdf-generator-with-email-sending-rabbitmq-dead-letter-queues-docker-using-node-js-6fc4fa638569?source=rss-e61f06fa3b81------2</link>
            <guid isPermaLink="false">https://medium.com/p/6fc4fa638569</guid>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[pdfkit]]></category>
            <category><![CDATA[rabbitmq]]></category>
            <dc:creator><![CDATA[Maria Ferreira]]></dc:creator>
            <pubDate>Tue, 15 Jul 2025 12:28:36 GMT</pubDate>
            <atom:updated>2025-07-15T12:28:36.165Z</atom:updated>
            <content:encoded><![CDATA[<p>In my last position I worked on a system that generates PDFs dynamically, sends them by email, and handles failures using queues, and recently I decided to recreate a simplified version of it as a personal project to refresh my memory and have it in my portfolio.</p><p>I am documenting it here both for future me and anyone else who might find it useful. You can check out the full code on GitHub:<br> 👉 <a href="https://github.com/marinspira/pdf-email-rabbitmq">https://github.com/marinspira/pdf-email-rabbitmq</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oR8fzVq05IBMQtpd.png" /></figure><h3>What I Wanted to Build</h3><p>Here is the idea:</p><ul><li>A <strong>REST API</strong> where I send a list of users + an email.</li><li>A <strong>PDF is generated</strong> based on that list.</li><li>The <strong>PDF is emailed</strong> to the address I sent.</li><li>If anything fails, the job is sent to a <strong>dead-letter queue (DLQ)</strong> for later inspection.</li><li>All of this runs inside <strong>Docker containers</strong>.</li></ul><p>So let’s break it down into components.</p><h3>What is RabbitMQ?</h3><p>RabbitMQ is a <strong>message broker</strong>. It sits between systems and helps them talk to each other <strong>asynchronously</strong> using queues.</p><p>In this project, instead of the API directly generating the PDF and sending the email (which could be slow or crash), the API simply <strong>puts a message (job) on a queue</strong>. Then a separate worker (or we can call consumer) service <strong>pulls jobs from the queue</strong> and does the heavy lifting — PDF generation and email sending.</p><p>This separation keeps the API fast and responsive, and the actual work can be retried or monitored independently.</p><h3>Setting Up the API (Producer)</h3><p>The API is written in Node.js using Express. It receives a POST /generate request with a list of users and an email address. Then it sends a message to RabbitMQ.</p><pre>app.post(&#39;/generate&#39;, async (req, res) =&gt; {<br>  const { users, email } = req.body;<br>  if (!users || !email) {<br>    return res.status(400).json({ error: &#39;Missing users or email&#39; });<br>  }<br><br>  const job = { users, email };<br>  channel.sendToQueue(&#39;pdf_jobs&#39;, Buffer.from(JSON.stringify(job)), {<br>    persistent: true<br>  });<br><br>  res.status(202).json({ message: &#39;Job queued&#39; });<br>});</pre><p>This part is stateless and fast. It doesn’t actually do any heavy work like generating PDFs — just hands off the job to RabbitMQ.</p><h3>🐰 RabbitMQ with Dead-Letter Queue</h3><p>RabbitMQ is a message broker. It sits in the middle and passes messages (jobs) from the API to the worker (consumer).</p><p>We also set up a <strong>dead-letter queue</strong> so that if a job fails (e.g., the worker crashes, the email can’t send), the job goes into a separate queue for inspection — instead of getting lost.</p><pre>await channel.assertQueue(&#39;pdf_jobs&#39;, {<br>  durable: true,<br>  deadLetterExchange: &#39;&#39;,<br>  deadLetterRoutingKey: &#39;pdf_dlq&#39;<br>});</pre><pre>await channel.assertQueue(&#39;pdf_dlq&#39;, { durable: true });</pre><p>When I learned this, gave me peace of mind. If something breaks, I can debug it later.</p><h3>🧑‍🔧 The Worker: Where the Magic Happens</h3><p>The worker listens to the pdf_jobs queue. When a job comes in, it:</p><ol><li>Generates a PDF using pdfkit.</li><li>Sends an email using nodemailer.</li><li>If anything throws an error, the message is sent to the DLQ.</li></ol><pre>channel.consume(&#39;pdf_jobs&#39;, async (msg) =&gt; {<br>  const job = JSON.parse(msg.content.toString());<br>  const filePath = `report-${Date.now()}.pdf`;<br><br>  try {<br>    await generatePDF(job.users, filePath);<br>    await sendEmail(job.email, filePath);<br>    channel.ack(msg);<br>  } catch (err) {<br>    console.error(&#39;Job failed:&#39;, err.message);<br>    channel.nack(msg, false, false); // Send to DLQ<br>  }<br>});</pre><p><strong>PDF generation</strong> is done with pdfkit. I just looped through the user list and added each to the doc.</p><pre>function generatePDF(users, filePath) {<br>  const doc = new PDFDocument();<br>  doc.pipe(fs.createWriteStream(filePath));<br>  users.forEach((u, i) =&gt; doc.text(`${i + 1}. ${u.name} - ${u.email}`));<br>  doc.end();<br>}</pre><p><strong>Sending email</strong> was trickier. At first, I got the infamous Missing credentials for &quot;PLAIN&quot; error. Turns out Gmail requires an App Password.</p><p>Once I fixed that, this did the trick:</p><pre>const transporter = nodemailer.createTransport({<br>  service: &#39;gmail&#39;,<br>  auth: {<br>    user: process.env.EMAIL_USER,<br>    pass: process.env.EMAIL_PASS<br>  }<br>});</pre><p>Important: you must set up <strong>2FA on your Google account</strong> and generate an <a href="https://myaccount.google.com/u/1/apppasswords">App Password</a> to make this work.</p><h3>🐳 Dockerizing Everything</h3><p>I’ve worked on projects before where running multiple services — like an API, a worker, and a message broker — required a lot of setup on different terminals or environments. Docker solves that by letting me spin up <strong>everything in isolated containers</strong> with one command. It ensures that:</p><ul><li>Everyone (including future me) runs the project the same way</li><li>Dependencies and runtime environments are consistent</li><li>I can run the API, worker, and RabbitMQ together locally without installing them globally</li></ul><p>Also, Docker Compose makes it super easy to connect services like Node.js apps and RabbitMQ with just a few lines of YAML.</p><p>Here is a snippet from docker-compose.yml:</p><pre>services:<br>  rabbitmq:<br>    image: rabbitmq:3-management<br>    ports:<br>      - &quot;5672:5672&quot;<br>      - &quot;15672:15672&quot;<br><br>  api:<br>    build: ./api<br>    ports:<br>      - &quot;3000:3000&quot;<br>    environment:<br>      - RABBITMQ_URL=amqp://rabbitmq<br>    depends_on:<br>      - rabbitmq<br><br>  worker:<br>    build: ./worker<br>    environment:<br>      - RABBITMQ_URL=amqp://rabbitmq<br>    depends_on:<br>      - rabbitmq</pre><p>Now I can run everything with:</p><pre>docker-compose up --build</pre><p>And I get:</p><ul><li>API on localhost:3000</li><li>RabbitMQ dashboard on localhost:15672</li><li>Worker consuming messages</li></ul><h3>🧪 Testing with Postman</h3><p>To test the API, I just fired up Postman:</p><ul><li>Method: POST</li><li>URL: <a href="http://localhost:3000/generate">http://localhost:3000/generate</a></li><li>Body:</li></ul><pre>{<br>  &quot;email&quot;: &quot;myemail@gmail.com&quot;,<br>  &quot;users&quot;: [<br>    { &quot;name&quot;: &quot;Alice&quot;, &quot;email&quot;: &quot;alice@example.com&quot; },<br>    { &quot;name&quot;: &quot;Bob&quot;, &quot;email&quot;: &quot;bob@example.com&quot; }<br>  ]<br>}</pre><p>After clicking “Send”, the worker picked up the job, generated a PDF, and I got an email with the file. Pretty satisfying.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bvVJO9PxUbBoP4a2.png" /></figure><p>To test failures, I literally added a throw new Error(&#39;simulate&#39;) inside the worker, and verified the message landed in the DLQ via the RabbitMQ dashboard.</p><p>Let me know if you’ve done something similar or have ideas for improvements. I’m always looking to learn better patterns for building these kinds of services.</p><p>Thanks for reading! :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6fc4fa638569" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[REST vs RESTful: Principles & Security Best Practices]]></title>
            <link>https://medium.com/@mariaferreira.developer/rest-vs-restful-its-6-principles-security-best-practices-d4ff8145e09a?source=rss-e61f06fa3b81------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4ff8145e09a</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[restful-api]]></category>
            <category><![CDATA[rest-api]]></category>
            <dc:creator><![CDATA[Maria Ferreira]]></dc:creator>
            <pubDate>Tue, 08 Jul 2025 16:23:21 GMT</pubDate>
            <atom:updated>2025-07-22T11:53:56.919Z</atom:updated>
            <content:encoded><![CDATA[<p>Other day I was casually watching a tech video (you know, the kind you put on in the background but end up fully sucked into), I stumbled upon something that honestly blew my mind:</p><p>👉 <strong>There’s a difference between REST and RESTful</strong>, and REST actually has <strong>six architectural principles</strong>.</p><p>It is like… what? It shows up to the architecture party in flip-flops and says, “Hey, I’m casual.”</p><p>I would been tossing around the term “REST API” for years without thinking too hard about what made it “RESTful” — and apparently, there is a whole structure behind it defined by Roy Fielding, and to be truly <strong>RESTful</strong>, your API has to follow <strong>all six of these principles</strong>:</p><h3>The 6 Principles of RESTful Architecture</h3><ol><li><strong>Client–Server Architecture</strong><br> The frontend and backend are separated concerns. They talk, but they don’t live together.</li><li><strong>Statelessness</strong><br> Each request from the client must contain all the information needed to process it. No sneaky session storage allowed.</li><li><strong>Cacheability</strong><br> Responses must define themselves as cacheable or not, to improve performance.</li><li><strong>Uniform Interface</strong><br> A standard way of communicating between client and server (think: HTTP methods, URLs, media types, etc.)</li><li><strong>Layered System</strong><br> You can have multiple layers (proxies, load balancers), and the client shouldn’t need to know how many.</li><li><strong>Code on Demand (optional)</strong><br> The server can send executable code to the client (like JavaScript). This one is rarely used.</li></ol><h3>REST API Security Best Practices</h3><h4><strong>Use HTTPS Always</strong></h4><p>Never allow HTTP. Secure your API with HTTPS (TLS). It’s the first layer of defense against man-in-the-middle (MITM) attacks.</p><h4><strong>Authentication &amp; Authorization</strong></h4><ul><li>Use <strong>OAuth 2.0</strong> or <strong>JWT (JSON Web Tokens)</strong> for token-based authentication.</li><li>Implement <strong>role-based access control (RBAC)</strong> or <strong>attribute-based access control (ABAC)</strong> depending on your needs.</li></ul><h4><strong>Rate Limiting &amp; Throttling</strong></h4><p>Protect your API from abuse or brute force attacks by setting limits using tools like:</p><ul><li>API Gateways (AWS API Gateway, Kong, NGINX)</li><li>Middleware (Express-rate-limit for Node.js)</li></ul><h4><strong>Input Validation &amp; Output Encoding</strong></h4><p>Sanitize and validate user input (avoid SQL injection, XSS, etc.).<br> Use libraries like:</p><ul><li>Joi or Zod (Node.js)</li><li>Marshmallow (Python)</li><li>Bean Validation (Java)</li></ul><h4><strong>Avoid Excessive Data Exposure</strong></h4><p>Don’t return everything. Use fields filtering or GraphQL for selective data. Also, avoid sending stack traces or internal info in error messages.</p><h4><strong>Secure Headers</strong></h4><p>Apply security headers like Content-Security-Policy (CSP):</p><p><strong>What it does: </strong>Controls which resources (scripts, styles, images, etc.) the browser is allowed to load and execute. It helps <strong>prevent XSS (Cross-Site Scripting)</strong> and <strong>data injection attacks</strong>.</p><p><strong>Why it’s important: </strong>Modern web apps load content from many sources. CSP helps enforce strict rules to limit what’s allowed, significantly reducing the attack surface.</p><p><strong>Example Header:</strong></p><pre>Content-Security-Policy: default-src &#39;self&#39;; script-src &#39;self&#39; https://apis.google.com</pre><p><strong>Explanation:</strong></p><ul><li>default-src &#39;self&#39;: Allow everything (scripts, styles, images, etc.) to load only from the same origin.</li><li>script-src &#39;self&#39; https://apis.google.com: Scripts can be loaded only from the same origin and Google&#39;s API domain.</li></ul><p>You can fine-tune policies for styles, fonts, frames, images, etc.</p><ul><li>X-Content-Type-Options</li><li>Strict-Transport-Security</li></ul><h4><strong>Keep Secrets Safe</strong></h4><p>Never hardcode (even in the beginning, because you might forget it!) secrets (API keys, tokens) in your source code. Use environment variables or secret management services like AWS Secrets Manager or Github Secrets.</p><h4><strong>Logging &amp; Monitoring</strong></h4><p>Track usage and errors but don’t log sensitive data. Integrate tools like:</p><ul><li>ELK Stack</li><li>Prometheus &amp; Grafana</li><li>Sentry</li></ul><h3>REST API Structural Guidelines</h3><p>A clean structure makes your API easy to use, maintain, and scale.</p><h4><strong>Versioning</strong></h4><ul><li>/api/v1/users</li><li>/api/v2/products</li></ul><h4><strong>Use nouns, never verbs</strong></h4><p>✅ GET /users<br>❌ GET /getUsers</p><h4><strong>Consistent resource naming</strong></h4><ul><li>Use <strong>plural nouns</strong>: /orders, /products</li><li>Nested resources: /users/{userId}/orders</li></ul><h4><strong>HTTP Methods for CRUD</strong></h4><ul><li>GET /users → List users</li><li>POST /users → Create user</li><li>GET /users/{id} → Get user by ID</li><li>PUT /users/{id} → Update user</li><li>DELETE /users/{id} → Delete user</li></ul><h4><strong>Use Query Parameters for Filtering</strong></h4><ul><li>GET /products?category=books&amp;sort=price_asc</li></ul><h4><strong>Standardized Responses</strong></h4><ul><li>Use proper status codes: 200 OK, 201 Created, 400 Bad Request, 401 Unauthorized, 404 Not Found</li><li>Response format (JSON): { &quot;status&quot;: &quot;success&quot;, &quot;data&quot;: {...} }</li><li>Error Handling { &quot;status&quot;: &quot;error&quot;, &quot;message&quot;: &quot;Invalid input&quot;, &quot;code&quot;: 400 }</li></ul><h3>Final Thoughts</h3><p>A REST API that is secure and well-structured isn’t just nice to have — it’s a <strong>necessity</strong>. With the growing number of integrations, mobile apps, and third-party consumers, prioritizing these best practices ensures performance, safety, and scalability.</p><p><strong>Build it clean. Secure it strong. Maintain it smart.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4ff8145e09a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Native (Expo) & Android API Level 35 — My Journey with the Gradle Bundle]]></title>
            <link>https://javascript.plainenglish.io/react-native-expo-android-api-level-35-my-journey-with-the-gradle-bundle-38761cf68b75?source=rss-e61f06fa3b81------2</link>
            <guid isPermaLink="false">https://medium.com/p/38761cf68b75</guid>
            <category><![CDATA[google-play-store]]></category>
            <category><![CDATA[expo]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Maria Ferreira]]></dc:creator>
            <pubDate>Tue, 08 Jul 2025 14:31:49 GMT</pubDate>
            <atom:updated>2025-07-23T12:46:25.647Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>React Native (Expo) &amp; Android API Level 35 — My Journey with the Gradle Bundle</strong></h3><p>Recently, I received a notification from Google Play about one of my already published React Native (Expo) apps:</p><blockquote><strong><em>“App must target Android 15 (API level 35) or higher.”</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Grt2pz3Njg_ZGtbxxzjOEQ.png" /></figure><h3>What Happened?</h3><p>Google Play now <strong>requires all new and updated apps</strong> to target <strong>API level 35 (Android 15)</strong>. My Expo app was targeting an older version.</p><p>Since I was using the <strong>custom dev client</strong> workflow (eas build with Expo + React Native), I had access to the native Android code — including the infamous <strong>Gradle files</strong>.</p><h3>What is a Gradle Bundle?</h3><p>If you’re new to this:</p><ul><li><strong>Gradle</strong> <strong>is the build system Android uses</strong>. It automates building, testing, packaging, and deploying Android apps.</li><li>A <strong>Gradle bundle</strong> refers to the <strong>complete build configuration for your app</strong>, usually defined in build.gradle files. This includes dependencies, SDK versions, and compilation settings.</li></ul><h3>How I Fixed the API Level Issue</h3><h4>1. Make sure you are using a custom dev client</h4><p>This fix assumes you have access to the native Android code (i.e., android/ folder is available).</p><h4>2. Update Gradle settings</h4><p>Open your android/build.gradle file (not app/build.gradle) and modify/add the following block inside buildscript:</p><pre>buildscript {<br>    ext {<br>        buildToolsVersion = findProperty(&#39;android.buildToolsVersion&#39;) ?: &#39;35.0.0&#39;<br>        minSdkVersion = Integer.parseInt(findProperty(&#39;android.minSdkVersion&#39;) ?: &#39;24&#39;)<br>        compileSdkVersion = Integer.parseInt(findProperty(&#39;android.compileSdkVersion&#39;) ?: &#39;35&#39;)<br>        targetSdkVersion = Integer.parseInt(findProperty(&#39;android.targetSdkVersion&#39;) ?: &#39;35&#39;)<br>        kotlinVersion = findProperty(&#39;android.kotlinVersion&#39;) ?: &#39;1.9.24&#39;<br><br>        ndkVersion = &quot;26.1.10909125&quot;<br>    }<br>}</pre><ul><li><strong>compileSdkVersion</strong>: SDK used during compilation. Must be 35.</li><li><strong>targetSdkVersion</strong>: SDK you are optimizing for. Must be 35 for Play Store.</li><li><strong>minSdkVersion</strong>: Oldest Android version your app supports. Adjust based on your needs.</li><li><strong>buildToolsVersion</strong>: Build tools version compatible with SDK 35.</li><li><strong>kotlinVersion</strong>: Needed if any dependency uses Kotlin.</li></ul><h4>3. Clean the Gradle Cache (CRITICAL!)</h4><p>Before rebuilding, <strong>clean out the old build artifacts</strong> to prevent caching issues:</p><pre>cd android<br>./gradlew clean</pre><p>Also, optionally clear the global Gradle cache (if you have had persistent problems):</p><pre>rm -rf ~/.gradle/caches/</pre><pre>./gradlew build</pre><p>Running ./gradlew build will recompile your Android app with the updated SDK and configuration. It ensures that the Gradle files are correctly processed and can help surface any issues before building with EAS.</p><blockquote><em>This step ensures the new SDK and build configurations are actually used during build time.</em></blockquote><h4>4. Rebuild the Custom Dev Client</h4><p>Since you’re using a custom dev client, you need to rebuild it:</p><pre>eas build --profile development --platform android</pre><p>This ensures your new Gradle settings are picked up in the build artifacts.</p><h4>5. Test on Android 15 (API 35)</h4><p>Before pushing to Google Play:</p><ul><li>Launch an Android 15 (API 35) emulator (or use a real device).</li><li>Install your new build.</li><li>Test critical flows to confirm everything runs as expected.</li></ul><h4>6. Build and Submit to Google Play</h4><p>Finally, do a production build and submit it:</p><pre>eas build --profile production --platform android<br>eas submit --platform android</pre><h3>Summary Checklist</h3><ul><li>Update android/build.gradle with API level 35 settings</li><li>Run ./gradlew clean to clear cached builds</li><li>Rebuild the custom dev client</li><li>Test on API 35 device/emulator</li><li>Submit via eas submit</li></ul><p>Feel free to reach out if you need help upgrading your Expo + Android setup — I am always happy to help fellow devs troubleshoot tricky problems!</p><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏️<strong>️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/@InPlainEnglish"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a> | <a href="https://twitch.tv/inplainenglish"><strong>Twitch</strong></a></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38761cf68b75" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/react-native-expo-android-api-level-35-my-journey-with-the-gradle-bundle-38761cf68b75">React Native (Expo) &amp; Android API Level 35 — My Journey with the Gradle Bundle</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying Java Spring Boot  microservices on Azure Container Apps with CI/CD]]></title>
            <link>https://medium.com/@mariaferreira.developer/deploying-java-spring-boot-on-azure-container-apps-with-ci-cd-a984b7102d6a?source=rss-e61f06fa3b81------2</link>
            <guid isPermaLink="false">https://medium.com/p/a984b7102d6a</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[azure-container-apps]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Maria Ferreira]]></dc:creator>
            <pubDate>Mon, 30 Jun 2025 20:06:38 GMT</pubDate>
            <atom:updated>2025-06-30T20:11:08.774Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deploying Java Spring Boot microservices on Azure Container Apps with CI/CD</h3><p>In this post, I’ll walk you through how I set up a CI/CD pipeline to deploy <strong>Java microservices</strong> to <strong>Azure Container Apps </strong>using <strong>Docker</strong> and <strong>GitHub Actions.</strong></p><p>This includes using the <strong>Azure CLI</strong>, building with Maven, <strong>containerizing with Docker</strong>, and <strong>automating deployments </strong>with <strong>GitHub</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/0*RCbw8-ZwXUoEPhER.png" /></figure><h3>Microservices Project Structure</h3><p>Here’s how the folder structure of the project is organized:</p><pre>microservices/<br>├── user-service/<br>│   ├── src/<br>│   ├── pom.xml<br>│   └── Dockerfile<br>├── product-service/<br>│   ├── src/<br>│   ├── pom.xml<br>│   └── Dockerfile<br>└── .github/<br>    └── workflows/<br>        └── ci.yml</pre><p>Each service (user-service and product-service) is an independent Spring Boot app with its own Dockerfile and pom.xml.</p><h3>Install and Configure Azure CLI</h3><p>Fist of all it is necessary that we install the CLI from Azure, and login into your Azure account <strong>to be able to manager our projects via the terminal.</strong></p><p>Then, lets set a subscription, require for all projects to group the cost (even if you are not going to spend anything like me).</p><p><strong>Install Azure CLI</strong></p><pre>brew update &amp;&amp; brew install azure-cli</pre><p><strong>Login to Azure</strong></p><pre>az login</pre><p><strong>List all subscriptions</strong></p><pre>az account list - output table</pre><p><strong>Set the active subscription</strong></p><pre>az account set - subscription &quot;&lt;your-subscription-name-or-id&gt;&quot;</pre><p><strong>Verify active subscription</strong></p><pre>az account show - output table</pre><h3>Build and Package the Java App</h3><p>Before containerizing our app, we need to compile and package it using Maven. This process generates the .jar file inside the target folder, which will be used as the executable by Docker.</p><p><strong>Generate .jar or the target folder using Maven:</strong></p><pre>mvn clean package</pre><ul><li><strong>clean</strong> removes previous builds</li><li><strong>package</strong> compiles and builds the .jar under the target/ folder.</li></ul><h3>Docker Image and Container Setup</h3><p><strong>1. Build the Docker Image</strong><br>Now that the .jar file has been generated, we can use it to build a Docker image.</p><pre>docker build -t marinspira/user-service:latest .</pre><ul><li><strong>-t </strong>is the tag for naming the image</li><li>marinspira: This is your <strong>Docker Hub username</strong>. It identifies the namespace (or repo owner) where the image will be stored.</li><li>user-service: This is the <strong>name of the Docker image</strong>, typically reflecting the microservice you&#39;re packaging (in this case, user-service).</li><li>:latest: This is the <strong>version tag</strong> of the image.</li><li>.<strong> </strong>tells Docker to look for a Dockerfile in the current directory</li></ul><p><strong>2. Push the Image to Docker Hub</strong><br>Once the image is ready, push it to your Docker Hub repository so that Azure can access it later.</p><pre>docker push marinspira/user-service:latest</pre><h3>Create Azure Resources</h3><h4><strong>Create Resource Group and Environment</strong></h4><p>To deploy our microservices to Azure Container Apps, we first need to create a <strong>Resource Group</strong> using az group create. <strong>This acts as a logical container to group and manage all related Azure resources in one place</strong> — such as environments, apps, and networking — making it easier to monitor.</p><p>Next, we create a <strong>Container Apps Environment</strong> with az containerapp env create. This environment provides the underlying infrastructure for running Container Apps, including shared networking, observability, and secure app-to-app communication.</p><p>By organizing services within the same environment, we ensure efficient management and potential interconnectivity between microservices.</p><pre>az group create - name microservices-rg - location eastus<br>az containerapp env create \<br> - name microservices-env \<br> - resource-group microservices-rg \<br> - location eastus</pre><h3>Deploy Container App to Azure</h3><p>This step provisions the actual <strong>Container App</strong> inside the environment we previously created at DockerHub. We give it a name (user-service), specify the resource group and environment, and <strong>link it to the Docker image</strong> (marinspira/user-service:latest) hosted on Docker Hub.</p><p>The target-port defines the internal port your app listens on (in this case, 8080), while ingress external <strong>allows public internet access</strong>. <strong>CPU and memory are also defined</strong> to allocate sufficient resources.</p><pre>az containerapp create \<br> - name user-service \<br> - resource-group microservices-rg \<br> - environment microservices-env \<br> - image marinspira/user-service:latest \<br> - target-port 8080 \<br> - ingress external \<br> - cpu 0.25 \<br> - memory 0.5Gi</pre><p><strong>Get public URL of the container</strong></p><p>After deployment, we run az containerapp show to <strong>retrieve the public URL</strong> (FQDN) of the container. It gives you the direct link to access your microservice from any browser or API client.</p><pre>az containerapp show \<br> - name user-service \<br> - resource-group microservices-rg \<br> - query properties.configuration.ingress.fqdn -o tsv</pre><p>At this stage, your application should be up and running, accessible via the retrieved public URL.</p><p>However, if you find that the container crashes or fails to start properly, it likely means there is an issue similar to the one I encountered below.</p><h3>Fixing Dockerfile for Java 21</h3><p>At first, my container failed to start due to a mismatch between the Java version used in development and the one available in the runtime environment. To resolve this, I create a Dockerfile to ensure both the <strong>build</strong> and <strong>runtime</strong> stages use <strong>Java 21</strong>.</p><pre># 1) Build JAR using Maven + Java 21<br>FROM maven:3.9.6-eclipse-temurin-21 AS build<br>WORKDIR /app<br>COPY pom.xml .<br>COPY src ./src<br>RUN mvn clean package<br><br># 2) Runtime using Java 21<br>FROM eclipse-temurin:21-jdk-alpine<br>WORKDIR /app<br>COPY --from=build /app/target/*.jar app.jar<br>EXPOSE 8080<br>ENTRYPOINT [&quot;java&quot;, &quot;-jar&quot;, &quot;app.jar&quot;]</pre><p>Rebuild &amp; push to Docker Hub</p><pre>docker build -t marinspira/user-service:latest .<br>docker push marinspira/user-service:latest</pre><p>Update Azure Container App with the new image</p><pre>az containerapp update \<br> - name user-service \<br> - resource-group microservices-rg \<br> - image marinspira/user-service:latest</pre><h3>CI/CD Setup with GitHub Actions</h3><p>To automate the deployment of our Java microservices to Azure Container Apps, we’ll set up a GitHub Actions workflow.</p><p>This CI/CD pipeline handles building the application, packaging it into Docker images, pushing those images to Docker Hub, and finally deploying them to Azure.</p><h4><strong>1. Create Service Principal</strong></h4><p>We need to create an Azure service principal with the appropriate permissions so GitHub Actions can authenticate and manage Azure resources on our behalf:</p><pre>az ad sp create-for-rbac \<br> - name &quot;github-actions-sp&quot; \<br> - role contributor \<br> - scopes /subscriptions/&lt;YOUR_SUBSCRIPTION_ID&gt; \<br> - sdk-auth</pre><p>This command outputs a JSON object with all the credentials required for GitHub to access Azure. These will be added to your GitHub secrets.</p><h4><strong>2. </strong>Create and a<strong>dd credentials to GitHub Secrets</strong></h4><p>This follow command will allow GitHub Actions to authenticate securely with Azure and manage resources during the CI/CD pipeline. Its output will be a JSON string containing credentials (clientId, clientSecret, tenantId, subscriptionId, and other details) that you need to save as a GitHub secret.</p><pre>az ad sp create-for-rbac \<br> - name github-action-deploy \<br> - role contributor \<br> - scopes /subscriptions/&lt;SUBSCRIPTION_ID&gt; \<br> - sdk-auth</pre><p>Now go to your GitHub repository settings and add the secrets you got.</p><ul><li><strong>DOCKERHUB_USERNAME</strong> and <strong>DOCKERHUB_TOKEN</strong> — used to authenticate Docker CLI to push images to Docker Hub.</li><li><strong>AZURE_CREDENTIALS</strong> — the full JSON output above.</li><li><strong>AZURE_CLIENT_ID</strong>, <strong>AZURE_CLIENT_SECRET</strong>, <strong>AZURE_TENANT_ID</strong>, <strong>AZURE_SUBSCRIPTION_ID</strong> — extracted from the same JSON (for extra granular use in steps).</li></ul><h4><strong>3. Create .github/workflows/ci.yml file:</strong></h4><p>I wanna trigger the workflow on every push or pull request to the main branch.</p><p>The pipeline should includes <strong>two main jobs</strong>:</p><ul><li><strong>Build and Push Docker Images</strong>: This job builds .jar files, containerizes them, and pushes them to Docker Hub.</li><li><strong>Deploy to Azure Container Apps:</strong> After pushing, this job deploys each service to its corresponding Azure Container App.</li></ul><p>our file is going to be something like:</p><pre>name: CI/CD Microservices to Azure<br>permissions:<br> id-token: write<br> contents: read<br>on:<br> push:<br> branches: [main]<br> pull_request:<br> branches: [main]<br>jobs:<br> build-and-push:<br> name: Build &amp; Push Docker Images<br> runs-on: ubuntu-latest<br> strategy:<br> matrix:<br> include:<br> - name: user-service<br> docker_image: marinspira/user-service<br> port: 8080<br> - name: product-service<br> docker_image: marinspira/product-service<br> port: 8081<br> env:<br> DOCKERHUB_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }}<br> DOCKERHUB_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }}<br> steps:<br> - uses: actions/checkout@v3<br> - uses: actions/setup-java@v4<br> with:<br> distribution: temurin<br> java-version: &#39;21&#39;<br> - name: Build JAR<br> run: mvn clean package -DskipTests<br> working-directory: ${{ matrix.name }}<br> - uses: docker/login-action@v2<br> with:<br> username: ${{ env.DOCKERHUB_USERNAME }}<br> password: ${{ env.DOCKERHUB_TOKEN }}<br> - name: Build Docker image<br> run: docker build -t ${{ matrix.docker_image }}:latest .<br> working-directory: ${{ matrix.name }}<br> - name: Push Docker image<br> run: docker push ${{ matrix.docker_image }}:latest<br> deploy-to-azure:<br> name: Deploy to Azure Container Apps<br> runs-on: ubuntu-latest<br> needs: build-and-push<br> strategy:<br> matrix:<br> include:<br> - app_name: user-service<br> docker_image: marinspira/user-service<br> port: 8080<br> - app_name: product-service<br> docker_image: marinspira/product-service<br> port: 8081<br> env:<br> AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}<br> AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}<br> AZURE_SUBSCRIPTION_ID: ${{ secrets.AZURE_SUBSCRIPTION_ID }}<br> AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}<br> steps:<br> - uses: actions/checkout@v3<br> - uses: azure/login@v1<br> with:<br> creds: ${{ secrets.AZURE_CREDENTIALS }}<br> - name: Update ingress<br> run: |<br> az containerapp ingress update \<br> - name ${{ matrix.app_name }} \<br> - resource-group microservices-rg \<br> - target-port ${{ matrix.port }}<br> - name: Deploy<br> run: |<br> az containerapp update \<br> - name ${{ matrix.app_name }} \<br> - resource-group microservices-rg \<br> - image ${{ matrix.docker_image }}:latest \<br> - cpu 0.25 \<br> - memory 0.5Gi</pre><h3>Utility Commands</h3><h4>Check current port</h4><p>Each containerized microservice runs on its own specific port, which determines where it listens for incoming network traffic. Before updating or troubleshooting, it’s important to verify the currently configured port for the service.</p><p>This command retrieves the port number that the Azure Container App is using to route external traffic to the internal container port for the product-service.</p><pre>az containerapp show \<br> - name product-service \<br> - resource-group microservices-rg \<br> - query &quot;properties.configuration.ingress.targetPort&quot;</pre><h4>Change container port</h4><p>If the port returned by the command above is incorrect or needs to be updated, you can change it using the command below. Replace 8081 with the port number your service actually listens on to ensure proper traffic routing:</p><pre>az containerapp ingress update \<br> - name product-service \<br> - resource-group microservices-rg \<br> - target-port 8081</pre><h3>Conclusion</h3><p>By following this guide, we now have a complete setup for:</p><ul><li>Building and packaging Java Spring Boot apps</li><li>Dockerizing and pushing images to Docker Hub</li><li>Deploying to Azure Container Apps</li><li>Automating the CI/CD process with GitHub Actions</li></ul><p>I hope this guide helps you avoid some of the bumps I hit and makes your own deployment journey smoother and more enjoyable.</p><p>If you have any questions or want to share your experiences, feel free to reach out :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a984b7102d6a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>