Lab 7 - RESTful API's

Why RESTful was Developed:

JSON

JSON Objects Objects are enclosed in curly braces {}

{
  "firstName": "Mary",
  "lastName": "Wise",
  "isStudent": false
}

A JSON list is an ordered collection of values, which are enclosed in square brackets []

[
  {"firstName": "John", "lastName": "Doe"},
  {"firstName": "Jane", "lastName": "Smith"},
  {"firstName": "Wei", "lastName": "Chen"}
]

fetchAPI

The Fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses.

Here’s a basic breakdown of how to use the Fetch API:

const educationData = { institution: 'MIT', studyType: 'BSc', area: 'Computer Science', startDate: '2019-08', endDate: '2023-05' };

const apiUrl = 'https://example.com/api/education';

fetch(apiUrl, {
  method: 'POST',  // or 'PUT' if updating
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(educationData)
})
.then(response => {
  if (!response.ok) {
    throw new Error('Network response was not ok');
  }
  return response.json();  // Parse JSON response into native JavaScript objects
})
.then(data => {
  console.log('Success:', data);
  alert('Education added successfully!');
})
.catch(error => {
  console.error('Error:', error);
  alert('Error adding education.');
});

Template <template> tag

HTML

<template id="userFormTemplate">
  <div class="user-form">
    <label for="name">Name:</label>
    <input type="text" id="name" name="name">
    <button type="button">Submit</button>
  </div>
</template>

JavaScript

document.getElementById('addFormBtn').addEventListener('click', function() {
  const template = document.getElementById('userFormTemplate');
  const clone = template.content.cloneNode(true); // Deep clone the template content
  document.body.appendChild(clone); // Append the cloned content to the body
});