In RESTFUL API call, there are two ends. One is Consumer or user and other is Provider or server
We will write Data Provider file or server side file in PHP. It is an array and JSON data.
Steps:
data.php
<?php
// Define your array data
$data = [
[“id” => 1, “name” => “John Doe”, “email” => “john@example.com”],
[“id” => 2, “name” => “Jane Smith”, “email” => “jane@example.com”],
[“id” => 3, “name” => “Alice Johnson”, “email” => “alice@example.com”]
];
// Set the content type to JSON
header(‘Content-Type: application/json’);
// Output the array data as JSON
echo json_encode($data);
?>
6. Save the file
7. Create another file api.html
Our client file or consumer is
api.html
<script>
// Function to fetch data from the endpoint and display it
function fetchDataAndDisplay() {
fetch(‘https://localhost/data/data.php’)
.then(response => {
// Check if response is successful
if (!response.ok) {
throw new Error(‘Failed to fetch data’);
}
// Parse the JSON response
return response.json();
})
.then(data => {
// Display the fetched data
document.write(‘<h2>Fetched Data With RESTFUL API:</h2>’);
document.write(‘<ul>’);
data.forEach(item => {
document.write(`<li>ID: ${item.id}, Name: ${item.name}, Email: ${item.email}</li>`);
});
document.write(‘</ul>’);
})
.catch(error => {
console.error(‘Error fetching data:’, error);
document.write(‘<p>Error fetching data. Please try again later.</p>’);
});
}
// Call the function to fetch data and display it
fetchDataAndDisplay();
</script>
It will fetch the data from data.php and display on the web browser.
The output will be
As you can see here in this link. Click here
After creating the files in data folder. open browser and type http://localhost/data/api.html
It will show the data fetched.
This is how you can make client/server app. In real world apps, the data is coming from database. When you login to facebook, you see list of friends it is a call to RESTFUL API fetch and display. When you connect to whatsApp, list of contacts is whatsapp.com/contacts and list of messages is whatsapp.com/messages
You can use any server side language like Python, Java, Dart, C#, PHP or whatevery to get the data from database convert it to JSON and then serve the data to client like Whatsapp, list of products in a shopping cart and here our simple example we used PHP on server side and JS on client end.
Must try above example it will clear your concepts and there is one question must about API during interview. RESTFUL pay kam kiya hai?
Hope you have understood.
Click Here To Download The Class Material (Note: copy this folder to your folder JavaScript on your disk)
[Download]