In the previous article, we learned about JavaScript Modules and Project Structure. Modern web applications rarely work alone. They constantly exchange data with servers and external services.
For example:
Weather applications get weather data from a server.
Banking apps retrieve account information.
E-commerce websites fetch product details.
Social media apps load posts and comments.
This communication is made possible through APIs and JSON.
In this article, we will learn:
What APIs are
What JSON is
Why APIs are important
JSON syntax
JSON methods
REST APIs
HTTP methods
Fetching API data
Sending data to servers
Practical examples
What is an API?
API stands for:
Application Programming Interface
An API acts as a bridge between two software applications.
Real-Life Example
Consider a restaurant.
Customer
↓
Waiter
↓
Kitchen
↓
Food
Here:
Waiter = API
The waiter takes requests from customers and delivers them to the kitchen.
Similarly:
Application
↓
API
↓
Server
Why APIs Are Needed
Without APIs:
Applications cannot communicate.
With APIs:
Applications exchange data efficiently.
Examples of APIs
Weather API
Payment API
Maps API
Social Media API
Banking API
Real-World Example
When you open a weather app:
Weather App
↓
Weather API
↓
Weather Server
↓
Weather Data
The app displays the received information.
What is JSON?
JSON stands for:
JavaScript Object Notation
JSON is the most common format used to exchange data between applications.
Why JSON?
JSON is:
Lightweight
Easy to read
Easy to write
Supported by most programming languages
JSON Example
{
"name":"Rahul",
"age":20,
"city":"Kolkata"
}
Understanding JSON Structure
{
"key":"value"
}
Example:
{
"name":"Rahul"
}
Here:
name → Key
Rahul → Value
JSON vs JavaScript Object
JavaScript Object:
let student =
{
name:"Rahul",
age:20
};
JSON:
{
"name":"Rahul",
"age":20
}
Difference:
JSON keys must be inside double quotes.
JSON Data Types
JSON supports:
| Type | Example |
|---|---|
| String | "Rahul" |
| Number | 20 |
| Boolean | true |
| Array | [1,2,3] |
| Object | {} |
| Null | null |
JSON Example
{
"name":"Rahul",
"age":20,
"student":true
}
JSON Arrays
Example:
{
"fruits":
[
"Apple",
"Mango",
"Orange"
]
}
Nested JSON
{
"student":
{
"name":"Rahul",
"age":20
}
}
JSON.stringify()
Converts JavaScript object into JSON string.
Example
let student =
{
name:"Rahul",
age:20
};
let jsonData =
JSON.stringify(student);
console.log(jsonData);
Output:
{"name":"Rahul","age":20}
JSON.parse()
Converts JSON string into JavaScript object.
Example
let data =
'{"name":"Rahul","age":20}';
let student =
JSON.parse(data);
console.log(student.name);
Output:
Rahul
What is a REST API?
REST stands for:
Representational State Transfer
REST API is the most common type of web API.
REST API Communication
Client
↓
HTTP Request
↓
Server
↓
HTTP Response
↓
Client
Example
Browser requests:
Get User Data
Server responds:
{
"id":1,
"name":"Rahul"
}
HTTP Methods
REST APIs use HTTP methods.
| Method | Purpose |
|---|---|
| GET | Retrieve data |
| POST | Send data |
| PUT | Update data |
| DELETE | Remove data |
GET Request
Used to retrieve data.
Example:
Get User Information
POST Request
Used to create new data.
Example:
Create New User
PUT Request
Used to update data.
Example:
Update User Profile
DELETE Request
Used to delete data.
Example:
Delete User Account
API Response Example
{
"id":1,
"name":"Rahul",
"city":"Kolkata"
}
Fetching Data from an API
JavaScript uses:
fetch()
Basic Syntax
fetch(url)
.then(response =>
response.json())
.then(data =>
console.log(data));
Example
fetch(
"https://jsonplaceholder.typicode.com/users"
)
.then(
response =>
response.json()
)
.then(
data =>
console.log(data)
);
How Fetch Works
Request Sent
↓
Server Receives Request
↓
Server Sends Response
↓
JavaScript Processes Data
Using Async/Await
Modern approach:
async function getUsers()
{
let response =
await fetch(
"https://jsonplaceholder.typicode.com/users"
);
let data =
await response.json();
console.log(data);
}
getUsers();
Reading API Data
Example API Response:
{
"name":"Rahul",
"age":20
}
Accessing data:
console.log(data.name);
Output:
Rahul
Displaying API Data on Webpage
HTML:
<h1 id="name"></h1>
JavaScript:
document.getElementById(
"name"
).innerHTML =
data.name;
Sending Data to Server
Using POST request.
Example
fetch(
"https://example.com/users",
{
method:"POST",
headers:
{
"Content-Type":
"application/json"
},
body:
JSON.stringify(
{
name:"Rahul"
}
)
}
);
Understanding POST Request
User Data
↓
JSON
↓
Server
↓
Database
Example Response
{
"message":
"User Created"
}
Handling API Errors
Example:
fetch(url)
.then(response =>
{
if(!response.ok)
{
throw new Error(
"API Error"
);
}
return response.json();
})
.then(data =>
console.log(data))
.catch(error =>
console.log(error));
Async/Await Error Handling
async function getData()
{
try
{
let response =
await fetch(url);
let data =
await response.json();
console.log(data);
}
catch(error)
{
console.log(error);
}
}
Practical Example – Display User
async function getUser()
{
let response =
await fetch(
"https://jsonplaceholder.typicode.com/users/1"
);
let user =
await response.json();
console.log(
user.name
);
}
getUser();
Output:
Leanne Graham
Practical Example – Display Posts
async function getPosts()
{
let response =
await fetch(
"https://jsonplaceholder.typicode.com/posts"
);
let posts =
await response.json();
console.log(posts);
}
getPosts();
Complete Program
<!DOCTYPE html>
<html>
<body>
<button onclick="loadUser()">
Load User
</button>
<h2 id="result">
</h2>
<script>
async function loadUser()
{
let response =
await fetch(
"https://jsonplaceholder.typicode.com/users/1"
);
let user =
await response.json();
document.getElementById(
"result"
).innerHTML =
user.name;
}
</script>
</body>
</html>
Output
After clicking:
Leanne Graham
appears on the webpage.
Real-Life Applications
APIs and JSON are used in:
Banking applications
Payment gateways
Weather apps
Social media platforms
E-commerce websites
Mobile applications
Companies like Google, Amazon, and Facebook rely heavily on APIs and JSON for data exchange.
Common Mistakes Beginners Make
Forgetting JSON.parse()
Wrong:
console.log(data.name);
when data is still a JSON string.
Forgetting await
Wrong:
let data =
response.json();
Correct:
let data =
await response.json();
Ignoring API Errors
Always use:
try-catch
or
.catch()
Advantages of APIs and JSON
Fast communication
Platform independent
Lightweight
Easy integration
Essential for modern applications
Conclusion
APIs and JSON are the backbone of modern web development. They enable applications to communicate with servers, exchange information, and provide dynamic user experiences.
Comments
Post a Comment