myHotTake

Tag: JavaScript fetch

  • How to Use Query Parameters in JavaScript Fetch Requests?

    If you enjoy this story, feel free to give it a like or share it with others who might find it helpful!


    I’m on a hiking adventure, preparing to explore a network of trails. These trails are like different endpoints on a server, each one leading to unique landscapes and experiences, much like how different endpoints return different data from a web server. Before I embark on my journey, I need to talk to the park ranger at the trailhead, who acts like the server, providing guidance and information.

    Now, I have a specific route in mind and certain preferences—like wanting to see waterfalls, avoid steep climbs, and find picnic spots. These preferences are akin to query parameters in a Fetch request. I need to communicate these details to the ranger, but instead of bombarding them with all my preferences at once, I write them down on a piece of paper.

    This piece of paper is like a query string in a URL. It organizes all my preferences in a neat list: “?waterfalls=true&steep=false&picnic_spots=true”. By handing this paper to the ranger, I’m effectively making a request with query parameters. The ranger understands my preferences immediately and can point me towards the trails that best match what I’m looking for.

    As I set off, I realize how efficient this system is. Without it, I’d have to explain my preferences from scratch every time I wanted information about a trail. And just like a Fetch request with query parameters, I can adjust my preferences and ask the ranger for new recommendations at any time, ensuring my hiking adventure is perfectly tailored to my desires.

    So, in this outdoor analogy, query parameters are like that paper with my trail preferences, allowing me to communicate precisely what I want to experience on my hike, making my exploration as seamless and enjoyable as possible.


    Back at the trailhead, I have my list of preferences ready to share with the park ranger. In JavaScript, this is similar to preparing a URL with query parameters for a Fetch request. Let’s say I’m building a small app to fetch data about hiking trails based on user preferences. Here’s how I might set it up:

    First, I’ll create a base URL, much like the main entrance to the park:

    const baseUrl = "https://api.hikingtrails.com/trails";

    Now, just like I jot down my preferences on paper, I’ll create an object to hold the query parameters:

    const preferences = {
      waterfalls: true,
      steep: false,
      picnic_spots: true
    };

    To convert these preferences into a query string, I’ll use URLSearchParams, a handy tool in JavaScript that formats the object into a string suitable for a URL:

    const queryString = new URLSearchParams(preferences).toString();

    This queryString is like my paper with trail preferences, ready to be handed to the park ranger. Now I’ll append it to the base URL:

    const fullUrl = `${baseUrl}?${queryString}`;

    With the full URL prepared, I’m ready to make a Fetch request. This is the equivalent of presenting my preferences to the park ranger and getting the best trail recommendations:

    fetch(fullUrl)
      .then(response => response.json())
      .then(data => {
        console.log('Trail recommendations:', data);
      })
      .catch(error => {
        console.error('Error fetching trails:', error);
      });

    This code tells the server exactly what I want—trails with waterfalls, no steep climbs, and picnic spots—just like my conversation with the ranger.

    Key Takeaways:

    1. Query Parameters as Communication Tools: In both hiking and JavaScript, query parameters help communicate specific preferences or needs effectively.
    2. URLSearchParams for Ease: Use URLSearchParams to easily convert objects into query strings, making your code cleaner and more readable.
    3. Dynamic and Flexible: Just as I can change my hiking preferences on the go, query parameters allow for dynamic and flexible data requests.
  • How Do HTTP Methods Mirror Art Gallery Management?

    If you find this story helpful, feel free to like or share it with others who might enjoy it too.


    I’m in charge of an art gallery. Each type of HTTP method is like a different interaction I have with the artwork in the gallery. As I walk through the halls, I encounter several scenarios that mirror these methods.

    First, there’s GET. It’s like when I stroll through the gallery just to admire the paintings. I’m not touching or changing anything; I’m simply retrieving the visual beauty to enjoy and understand it. It’s a peaceful walk where I absorb the information displayed.

    Then, I come across POST. Here, I have a blank canvas, and I decide to add a brand-new painting to the gallery. I carefully create and hang it on the wall. This action is about contributing something new, just like sending data to a server to create a new resource.

    Next is PUT, which is like when I see a painting that’s a bit worn out. I take it down, restore it completely, and then hang it back up. It’s the same spot and context, but the painting is now refreshed. It’s about updating an existing resource with a full makeover.

    As I continue, I encounter DELETE. There’s an old painting that doesn’t fit the theme anymore, and I decide to take it down permanently. Once it’s removed, that empty wall space signifies it’s no longer part of the gallery, akin to removing a resource entirely.

    Finally, there’s PATCH. This is when I notice a small scratch on a painting. Instead of redoing the whole artwork, I just touch up that specific area. It’s a minor update, addressing only the part that needs change, similar to modifying part of a resource without altering the entirety.

    Through these actions, I manage and curate the gallery, ensuring it’s always up-to-date and visually appealing. That’s how I understand the differences between GET, POST, PUT, DELETE, and PATCH in the digital world.


    In our art gallery, each interaction with the paintings can be translated into JavaScript code using the Fetch API, which allows us to perform HTTP requests. Let’s see how each method plays out in this context.

    JavaScript Code Examples

    1. GET: Admiring the Paintings
    • In JavaScript, I use the GET method to fetch data. It’s like looking at a painting without altering it.
       fetch('https://api.artgallery.com/paintings')
         .then(response => response.json())
         .then(data => console.log('Admiring the paintings:', data))
         .catch(error => console.error('Error fetching paintings:', error));
    1. POST: Adding a New Painting
    • When I add a new painting, I use POST to send data to the server to create something new.
       fetch('https://api.artgallery.com/paintings', {
         method: 'POST',
         headers: {
           'Content-Type': 'application/json'
         },
         body: JSON.stringify({ title: 'Sunset Bliss', artist: 'Jane Doe' })
       })
       .then(response => response.json())
       .then(data => console.log('New painting added:', data))
       .catch(error => console.error('Error adding painting:', error));
    1. PUT: Restoring an Old Painting
    • Here, PUT is used to update an entire resource, similar to fully restoring a painting.
       fetch('https://api.artgallery.com/paintings/1', {
         method: 'PUT',
         headers: {
           'Content-Type': 'application/json'
         },
         body: JSON.stringify({ title: 'Sunset Bliss Restored', artist: 'Jane Doe' })
       })
       .then(response => response.json())
       .then(data => console.log('Painting restored:', data))
       .catch(error => console.error('Error restoring painting:', error));
    1. DELETE: Removing an Outdated Painting
    • In this scenario, DELETE removes a painting from the gallery permanently.
       fetch('https://api.artgallery.com/paintings/1', {
         method: 'DELETE'
       })
       .then(() => console.log('Painting removed'))
       .catch(error => console.error('Error removing painting:', error));
    1. PATCH: Touching Up a Specific Area
    • PATCH is used for minor updates, like fixing a small scratch on a painting.
       fetch('https://api.artgallery.com/paintings/1', {
         method: 'PATCH',
         headers: {
           'Content-Type': 'application/json'
         },
         body: JSON.stringify({ title: 'Sunset Bliss Updated' })
       })
       .then(response => response.json())
       .then(data => console.log('Painting touched up:', data))
       .catch(error => console.error('Error touching up painting:', error));

    Key Takeaways

    • GET retrieves data without altering it, like admiring a painting.
    • POST creates a new resource, similar to adding a new painting to the gallery.
    • PUT updates an entire resource, akin to fully restoring a painting.
    • DELETE removes a resource, just as taking down a painting.
    • PATCH partially updates a resource, like making small corrections to a painting.
  • How Does REST Shape JavaScript API Design?

    If you enjoy this story, feel free to give it a like or share it with someone who might appreciate it.


    I’m the owner of a chain of coffee shops called Java Express. Each shop is with activity, yet they all operate under a simple, unified system that keeps everything running smoothly. This system is what I call REST, short for “Relaxed Espresso Shop Transactions.”

    In my coffee shops, our menu is like an API’s resources. Each item—whether it’s a cappuccino, a latte, or a bagel—is an endpoint that customers, like clients in an API, can access. When a customer walks in, they don’t need to see the chaos behind the counter; they simply place an order at the register.

    Now, here’s where it gets interesting. Each shop, though independently run, follows a set of rules that makes the experience the same no matter where you go. This is akin to REST’s principles guiding the design of an API. Each order placed is like an HTTP request. A customer asks for a cappuccino (a GET request), or maybe they want to add extra syrup (a POST request). If they decide to cancel an order, that’s a DELETE request.

    The baristas, my servers, know exactly what to do with each request. They fetch the right ingredients, make the drink, and serve it with a smile. They follow a protocol that’s consistent across all locations, much like how REST APIs use standard HTTP methods to ensure uniformity. This consistency ensures that any customer, or client, knows exactly how to interact with my shops without learning a new system each time.

    Moreover, the menus are designed to be stateless. After a customer places an order, they can leave and come back later to place a new one without needing to remember their previous orders. This mirrors how RESTful APIs handle client-server interactions, where each request is independent and doesn’t rely on stored data.

    By running my coffee shops with this RESTful approach, I ensure they are scalable and efficient, providing a seamless experience for every customer. Just like how RESTful design influences APIs to be easy to use, reliable, and scalable, my coffee shops thrive on simplicity and consistency.


    Continuing with the analogy, imagine I’ve decided to automate some processes in my coffee shops using a bit of JavaScript magic. This will help streamline operations and ensure that my RESTful approach is even more efficient.

    To start, I need a way to handle orders programmatically. In JavaScript, I might write a function to simulate making a request to my coffee shop API. Here’s a simple example using fetch to get a list of available menu items:

    async function fetchMenu() {
      try {
        const response = await fetch('https://javaexpress.com/api/menu');
        const menu = await response.json();
        console.log('Menu items:', menu);
      } catch (error) {
        console.error('Error fetching menu:', error);
      }
    }
    
    fetchMenu();

    In this code, I’m making a GET request to the virtual API of Java Express. This is like a customer walking in and asking to see the menu. The fetch function is my means of communication, ensuring I can request resources from the server.

    Next, let’s say a customer wants to order a cappuccino. I’d write a POST request to simulate placing that order:

    async function orderCappuccino() {
      try {
        const response = await fetch('https://javaexpress.com/api/orders', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ item: 'Cappuccino', quantity: 1 })
        });
    
        const orderConfirmation = await response.json();
        console.log('Order confirmed:', orderConfirmation);
      } catch (error) {
        console.error('Error placing order:', error);
      }
    }
    
    orderCappuccino();

    This snippet demonstrates how a POST request can be used to send data to the server, similar to a customer placing an order at the register. The server processes the order and returns a confirmation, just like a barista confirming an order.

    Lastly, if a customer changes their mind and wants to cancel the order, we can simulate a DELETE request:

    async function cancelOrder(orderId) {
      try {
        const response = await fetch(`https://javaexpress.com/api/orders/${orderId}`, {
          method: 'DELETE'
        });
    
        if (response.ok) {
          console.log('Order canceled successfully.');
        } else {
          console.error('Failed to cancel order.');
        }
      } catch (error) {
        console.error('Error canceling order:', error);
      }
    }
    
    cancelOrder(12345); // Example order ID

    This code illustrates how a DELETE request removes a resource, akin to canceling an order in the shop.

    Final Thoughts:

    • RESTful Design: REST principles ensure that APIs are consistent, scalable, and easy to use, much like the standardized operations in Java Express.
    • JavaScript and APIs: JavaScript, with tools like fetch, allows us to interact with APIs effectively, simulating customer interactions in a coffee shop.
    • HTTP Methods: Understanding the use of GET, POST, and DELETE methods is crucial for interacting with RESTful services, just as customers understand how to order, modify, and cancel orders in a shop.