An API, or application programming interface, is a set of defined rules that enable different applications to communicate with each other. It acts as an intermediary layer that processes data transfers between systems, letting companies open their application data and functionality to external third-party developers, business partners, and internal departments within their companies.
An API, or Application Programming Interface, is a set of rules and protocols that allows different software applications to communicate with each other. It serves as an intermediary between different software systems, enabling them to interact and exchange data in a standardized and controlled manner.
APIs define the methods, data formats, and conventions that developers should use when building software applications that need to integrate with a particular system or service. They provide a consistent interface that abstracts away the complexities of the underlying system, making it easier for developers to utilize the functionalities provided by that system.
APIs can be used in various contexts. They can be used to integrate different components within a software application, allowing different modules or libraries to work together seamlessly. APIs are also commonly used in web development to enable communication between web servers and client-side applications. Additionally, APIs are used extensively in the integration of different software systems, such as social media platforms, payment gateways, mapping services, and many other third-party services.
APIs are typically accessed through defined endpoints, which are specific URLs or addresses that allow developers to make requests and receive responses. These requests and responses are usually formatted using standard data exchange formats such as JSON (JavaScript Object Notation) or XML (eXtensible Markup Language).
What is JSON API
JSON, which stands for JavaScript Object Notation, is a lightweight data interchange format that is widely used for transmitting and storing data. It is a text-based format that is easy for humans to read and write, and it is also easy for machines to parse and generate.
JSON is based on a subset of the JavaScript programming language syntax, but it can be used with any programming language that supports parsing and generating JSON data. It has become a popular choice for data exchange in web services and APIs because of its simplicity and flexibility.
JSON represents data as key-value pairs, organized into objects and arrays. An object is an unordered collection of key-value pairs, where each key is a unique identifier and each value can be of any valid JSON data type (such as a string, number, boolean, object, or array). Arrays, on the other hand, are ordered collections of values, where each value can also be any valid JSON data type.
To host an API in Github, you need to follow the given steps
Step-1:Create a new Repository
Step-2:Upload your JSON file to the Repository
Step-3:host your repository to Github pages
Step-4:locate your API using https://{github page link}/json_file_name.json
Fetch Data in web page using API
To obtain data from an API and exhibit it on a webpage, you can utilize JavaScript's built-in fetch API or opt for libraries like axios. In this illustration, I will showcase the implementation using the fetch API, which comes integrated with modern browsers. Here's a step-by-step guide:
Fetch Data from API
Write a JavaScript script that employs the fetch API to retrieve data from the API and then updates the HTML content with the acquired data. For this example, let's assume we have a simple JSON API that returns a list of users.
Fetch Data from API
Make sure to replace 'https://example.com/api/users' with the actual URL of the API you wish to fetch data from. This script fetches data from the API, parses the JSON response, and dynamically updates the data-container with the user information retrieved from the API.
Remember that if the API requires authentication or has specific headers or request parameters, you'll need to include them in the fetch request accordingly. Additionally, consider error handling and displaying loading indicators while the data is being fetched.
CRUD Operation in API
CRUD operations in API refer to the standard operations that can be performed on resources through the API. CRUD stands for Create, Read, Update, and Delete, which correspond to the four basic operations that can be applied to most data resources. These operations are the foundation of many web applications and APIs that interact with databases or data storage.
Create
const newUser = {
name: 'John Doe',
email: 'john.doe@example.com'
};
const apiUrl = 'https://example.com/api/users';
// Perform the POST request to insert the new user data
fetch(apiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(newUser)
})
.then(response => response.json())
.then(data => {
console.log('New user inserted:', data);
})
.catch(error => {
console.error('Error inserting new user:', error);
});
Read
// Function to fetch data from the API
function fetchData() {
const apiUrl = 'https://api.example.com/data'; // Replace with your API endpoint URL
fetch(apiUrl)
.then(response => {
// Check if the response status is successful
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json(); // Parse the response body as JSON
})
.then(data => {
// The API response data will be available here
console.log(data);
// You can now process the data or display it on the webpage
// For example, if you have an HTML element with id="data-container":
// const dataContainer = document.getElementById('data-container');
// dataContainer.innerHTML = JSON.stringify(data, null, 2);
})
.catch(error => {
// Handle any errors that occurred during the fetch process
console.error('Error fetching data:', error);
});
}
// Call the fetchData function to fetch data from the API
fetchData();
Update
const updateUserData = {
name: 'Updated User',
email: 'updateduser@example.com',
// Add any other fields you want to update
};
const userIdToUpdate = 1; // Replace with the ID of the user you want to update
fetch(`https://example.com/api/users/${userIdToUpdate}`, {
method: 'PUT', // Use 'PUT' method for updating
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(updateUserData),
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(updatedUser => {
console.log('User updated successfully:', updatedUser);
// Handle the updated user data here, if needed
})
.catch(error => {
console.error('Error updating user:', error);
});
Delete
const userIdToDelete = 1; // Replace this with the ID of the user you want to delete
fetch(`https://example.com/api/users/${userIdToDelete}`, {
method: 'DELETE'
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
console.log('User deleted successfully:', data);
})
.catch(error => {
console.error('Error deleting user:', error);
});
Creating a Dynamic Website using API
In API, the term iframe stands for Inline Frame. The ‘iframe’ tag creates a
rectangular area within the content where a different document with scroll
bars and borders, may be displayed by the browser. To embed another
document inside the current API document, use an inline frame. An
iframe element's reference can be specified using the
API iframe name property. iframes are essentially used to display a
webpage inside the one that is now shown. The URL of the document that
contains the iframe is specified using the 'src' attribute
Live Search
In this example, We are going to learn live search a Github User. You can also use this to search data from your API
Live Search with API
GitHub User Search
Creating Multiple Element in HTML without copying elements and displaying dynamic data from APIJSON Data DisplayCreate a different webpage without creating them using APIDynamic Web Page with Fetch API