codingNito
Loading...

API

About API

What is API

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.

What we are going to learn in API


What is API

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.

{ "name": "John Doe", "age": 30, "city": "New York", "hobbies": ["reading", "traveling", "photography"], "isStudent": false }

How to Create a JSON API

To create a Json API, you need to create a json object and host it into the srver to create a JSON API

{ "name": "John Doe", "age": 30, "email": "john.doe@example.com", "address": { "street": "123 Main St", "city": "New York", "country": "USA" }, "hobbies": ["reading", "cooking", "hiking"] }

Hosting API in Github

To host an API in Github, you need to follow the given steps


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:

<!DOCTYPE html> <html> <head> <title>Fetch Data from API</title> </head> <body> <div id="data-container"> <!-- Data will be displayed here --> </div> </body> </html>

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.

<!DOCTYPE html> <html> <head> <title>Fetch Data from API</title> </head> <body> <div id="data-container"> <!-- Data will be displayed here --> </div> </body> </html>

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

<!DOCTYPE html> <html> <head> <title>Live Search with API</title> <style> #searchInput { width: 300px; padding: 10px; font-size: 16px; } #searchResults { margin-top: 10px; } .user { display: block; padding: 5px; border-bottom: 1px solid #ccc; } </style> </head> <body> <h1>GitHub User Search</h1> <input type="text" id="searchInput" placeholder="Search GitHub users..."> <div id="searchResults"></div> </body> </html> Creating Multiple Element in HTML without copying elements and displaying dynamic data from API <!DOCTYPE html> <html> <head> <title>JSON Data Display</title> <style> #data-container { margin: 20px; } .data-item { margin-bottom: 10px; } .data-label { font-weight: bold; } .data-value { margin-left: 10px; } </style> </head> <body> <div id="data-container"></div> </body> </html> Create a different webpage without creating them using API <!DOCTYPE html> <html> <head> <title>Dynamic Web Page with Fetch API</title> <style> #data-container { margin: 20px; } .data-item { margin-bottom: 10px; } .data-label { font-weight: bold; } .data-value { margin-left: 10px; } </style> </head> <body> <div id="data-container"></div> </body> </html>