API + Network Calls + Storages | Javascript Hindi Course For Beginners ( 2023 ) #12

 

API

API allows different software systems to communicate with each other. For example, imagine you are building a website or an app that needs to display data from a third-party service, such as weather data or stock prices. Rather than building that functionality from scratch, you can use the third-party service's API to access that data and display it on your site or app.
APIs are usually provided by companies or organisations that want to share data or functionality with developers. Developers can then use the API to access that data or functionality and integrate it into their own applications.
There are many different types of APIs, but they all serve the same purpose: to allow different software systems to communicate and work together.
 
FREE API FOR PRACTICE - https://jsonplaceholder.typicode.com All HTTP methods are supported. You can use http or https for your requests. // REST API GET /posts GET /posts/1 POST /posts PUT /posts/1 PATCH /posts/1 DELETE /posts/1
 

Fetch API

The Fetch API provides a simple and consistent interface for making network requests, such as fetching data from an API. It uses Promises, a modern JavaScript feature that allows asynchronous operations to be handled in a more readable and maintainable way.
 
// Basic Fetch API Struture const proimse = fetch(url,options) // By default GET // Getting data from api is two step process // Fetch API Return Promise here fetch('https://api.example.com/data') .then(response => { // here in this block we get response after resolving fetch promise // response contains various usefull information such as // status code ,headers and status text // then we parse coming response into json if data type send from server is json type // there are server data can be send by server .text() .formData() .blob() etc.. // json() method again return promise response.json() }) .then(data => { // now here we finaly get our data console.log(data); }) .catch(error => { // if some issue is caused during api call // then we catch that issue here console.error('Error:', error); });
 

Headers

Headers are extra information passed during network calls from server to client and client to server
Header Response → Server to Client
Header Request → Client to Server
 
Examples →
headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36', } // this header will send your device information to server
headers: { 'Content-Type', 'application/json } // this header will tell server which type of data
headers: { Authorization', `Bearer ${accessToken}` } // this header will tell server about current loggedin user
 
 

Types of Network Calls

GET: This is the most common type of network call, used to retrieve data from a server. A GET request is sent to the server with a URL and any required parameters, and the server responds with the requested data.
// For getting posts fetch('https://jsonplaceholder.typicode.com/posts') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error));
 
POST requests are used to send data to the server, typically to create or update a resource. The data is sent in the body of the request and can be in various formats, such as JSON or form data.
// For Creating New Posts const newPost = { title: 'My New Post', body: 'This is the body of my new post.', userId: 1 }; fetch('https://jsonplaceholder.typicode.com/posts', { method: 'POST', body: JSON.stringify(newPost), headers: { 'Content-type': 'application/json; charset=UTF-8', }, }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error));
 
PUT requests are similar to POST requests in that they are used to send data to the server to create or update a resource. However, unlike POST requests, PUT requests are idempotent, meaning that sending the same request multiple times has the same effect as sending it once.
const updatedPost = { title: 'My Updated Post', body: 'This is the updated body of my post.', }; fetch('https://jsonplaceholder.typicode.com/posts/1', { method: 'PUT', body: JSON.stringify(updatedPost), headers: { 'Content-type': 'application/json; charset=UTF-8', }, }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error));
PATCH requests are used to update a resource on the server with partial data. Unlike PUT requests, which replace the entire resource, PATCH requests only modify the specified fields.
 
 
DELETE requests are used to delete a resource on the server. Like PUT requests, DELETE requests are idempotent.
fetch('https://jsonplaceholder.typicode.com/posts/1', { method: 'DELETE' }) .then(response => { if (response.ok) { console.log('Post deleted successfully'); } else { console.log('Failed to delete post'); } }) .catch(error => console.error(error));
 

Cookies

 
Cookies are a way to store small amounts of data on a user's computer. They are often used to remember information about the user, such as login status or preferences. Cookies can be accessed and manipulated using JavaScript.
To create a cookie in JavaScript, you can use the document.cookie property. The syntax for setting a cookie is:
document.cookie = "name=value; expires=expiration_date; path=path_value; domain=domain_value; secure";
  • name is the name of the cookie
  • value is the value of the cookie
  • expires is the expiration date of the cookie (optional)
  • path is the path on the server where the cookie will be available (optional)
  • domain is the domain of the server where the cookie will be available (optional)
  • secure indicates that the cookie can only be sent over a secure connection (optional)
For example, to set a cookie named "username" with a value of "JohnDoe" that expires in one hour, you could use the following code:
document.cookie = "username=JohnDoe; expires=" + new Date(Date.now() + 3600000).toUTCString();
Reading Cookies:
To read a cookie in JavaScript, you can use the document.cookie property. The document.cookie property returns a string containing all the cookies associated with the current document. You can parse the string to get the value of a specific cookie. For example, to get the value of a cookie named "username", you could use the following code:
let cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { let cookie = cookies[i].trim(); if (cookie.startsWith("username=")) { let username = cookie.substring("username=".length, cookie.length); console.log(username); break; } }
Deleting Cookies:
To delete a cookie in JavaScript, you can set its expiration date to a date in the past. For example, to delete a cookie named "username", you could use the following code:
document.cookie = "username=; expires=" + new Date(0).toUTCString();
Security Considerations:
Cookies have some security concerns, such as the possibility of cookie theft or cookie-based attacks. As a result, newer technologies like web storage (which includes the localStorage and sessionStorage APIs) and HTTP-only cookies have been developed to provide more secure and flexible ways of storing data on the client side.
 
Note:
The maximum storage capacity of cookies is 4KB.
 

LocalStorage

LocalStorage is a way to store key-value pairs in a user's browser. It is often used to store small amounts of data that need to persist across multiple sessions or pages. LocalStorage can be accessed and manipulated using JavaScript.
Creating LocalStorage Items:
To create a LocalStorage item in JavaScript, you can use the localStorage.setItem() method. The syntax for setting a LocalStorage item is:
localStorage.setItem('key', 'value');
  • key is the name of the LocalStorage item
  • value is the value of the LocalStorage item
For example, to set a LocalStorage item named "username" with a value of "JohnDoe", you could use the following code:
localStorage.setItem('username', 'JohnDoe');
Reading LocalStorage Items:
To read a LocalStorage item in JavaScript, you can use the localStorage.getItem() method. The syntax for getting a LocalStorage item is:
localStorage.getItem('key');
  • key is the name of the LocalStorage item
For example, to get the value of a LocalStorage item named "username", you could use the following code: let username = localStorage.getItem('username'); console.log(username);
let username = localStorage.getItem('username'); console.log(username);
Deleting LocalStorage Items:
To delete a LocalStorage item in JavaScript, you can use the localStorage.removeItem() method. The syntax for removing a LocalStorage item is:
localStorage.removeItem('key');
  • key is the name of the LocalStorage item
For example, to remove a LocalStorage item named "username", you could use the following code:
localStorage.removeItem('username');
Clearing LocalStorage:
To clear all LocalStorage items in JavaScript, you can use the localStorage.clear() method. The syntax for clearing LocalStorage is:
localStorage.clear();
Security Considerations:
LocalStorage is generally considered to be a more secure and flexible way of storing data on the client side than cookies. However, it is still important to be aware of security concerns such as cross-site scripting (XSS) attacks and data leakage. As a result, it is recommended to only store data in LocalStorage that is not sensitive or critical.
 

Session Storage

 
SessionStorage is a way to store data in a user's browser using JavaScript that is scoped to a particular browsing session. SessionStorage items are stored on the user's computer and can be accessed and manipulated using JavaScript.
  • SessionStorage items are cleared when the user closes their browser or the tab that created them.
  • SessionStorage items can only be accessed and manipulated by scripts running on the same page that created them.
  • SessionStorage has a maximum storage capacity of 5-10 MB per domain, depending on the browser.
Using SessionStorage:
To use SessionStorage in your JavaScript code, you can use the sessionStorage object. This object has methods for setting and getting values:
  • sessionStorage.setItem(key, value): Sets a key-value pair in the SessionStorage object. If the key already exists, it will be overwritten.
  • sessionStorage.getItem(key): Gets the value associated with the given key in the SessionStorage object. If the key does not exist, it returns null.
  • sessionStorage.removeItem(key): Removes the key-value pair associated with the given key from the SessionStorage object.
  • sessionStorage.clear(): Clears all key-value pairs from the SessionStorage object.
 
Here are some examples of how to use SessionStorage:
// Set a value in SessionStorage sessionStorage.setItem('username', 'johndoe'); // Get a value from SessionStorage const username = sessionStorage.getItem('username'); // Remove a value from SessionStorage sessionStorage.removeItem('username'); // Clear all values from SessionStorage sessionStorage.clear();
Choosing Between SessionStorage and LocalStorage:
When deciding whether to use SessionStorage or LocalStorage, consider the following factors:
  • How long do you need the data to persist? If you need the data to persist across multiple browsing sessions or even after the user closes their browser, use LocalStorage. If the data only needs to persist for a single browsing session, use SessionStorage.
  • How will the data be used? If the data needs to be shared across multiple pages or scripts on the same domain, use LocalStorage. If the data only needs to be used by a single script or page, use SessionStorage.