Home > Software engineering >  How to consume a REST API properly on a multi page website
How to consume a REST API properly on a multi page website

Time:12-03

What is the best approach or best practice to consume a REST API within a multi-paged website on client side?

Lets assume I have the following REST API defined

/product -> all products, high level information 
/product/{id} -> detailed product information about product with given id

Further assume that my website has two .html pages, index.html and detail.html.

Inside the index.html I would query all products with high level information from my REST API with an AJAX call in Javascript. I then alter a table element inside the index.html page with the received JSON and display the high level information of each product inside this table.

Each table entry also has a link to the detailed product information, e.g. url/products/42.

Now to the interesting part. If I press the link of one specific product and want to show the detail.html page with detailed information about the pressed product id, how to I tell the Javascript inside detail.html which product the user pressed and is to be queried from the REST API?

I know how I perform these REST API calls in a native mobile app, since I always know, which element a user has pressed. I am a little bit lost how to do this on a multi paged website application.

Thanks to enrich my mind :)

CodePudding user response:

There are many ways to achieve what you want. Here some leads with basic code examples to show you the logic.

You could generate links like url/detail.html?product=42 then when detail page is loading extract parameter from url using something like

// detail.html
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function() {
  const queryString = window.location.search;
  console.log(queryString);
  //?product=42
  const urlParams = new URLSearchParams(queryString);
  const product = urlParams.get('product')
  console.log(product);
  // 42
  // here request your api with your product
});

You also could use click event on link

<!--index.html-->
<div id="container">
  <!-- some html -->
  <a href="javascript:void(0)" onclick="loadProduct(42)">
</div>
<script type="text/javascript" src="yourJS.js"></script>
//yourJS.js
let loadProduct = (product) => {
  // request API then for example use your detail.html as template to parse response 
  // and inject into html
};
  • Related