myHotTake

Tag: REST API

  • 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.