Skip to main content

Python type() Function

When learning Python, you will work with different types of data, such as numbers, text, decimal values, and Boolean values. Python provides several built-in functions to help you work with these data types. One of the most useful functions is the type() function . The type() function tells you the data type of a value or variable. It helps you understand what kind of data Python is working with and can make debugging your programs easier. For example, consider these variables: age = 20 price = 99.50 name = "Rahul" is_student = True Although all four variables store data, their data types are different. Python allows us to check these types using type() . Let's understand how it works with simple examples. 1. What Is the type() Function in Python? The type() function is a built-in Python function that returns information about the type of an object. In beginner-level programming, you can use it to check whether a value is an integer, a floating-point number, a string,...

JavaScript APIs and JSON – Communicating with Servers

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:

TypeExample
String"Rahul"
Number20
Booleantrue
Array[1,2,3]
Object{}
Nullnull

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.

MethodPurpose
GETRetrieve data
POSTSend data
PUTUpdate data
DELETERemove 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

Popular posts from this blog

Understanding Comments in Java: A Beginner’s Guide

When learning Java programming, one of the first concepts you’ll come across is comments . Comments may not affect how a program runs, but they play a crucial role in making code more understandable, readable, and maintainable. Let’s dive deeper into what comments are, why they’re important, and the different types of comments in Java. What are Comments in Java? A comment in Java is a piece of text written within a program that is ignored by the compiler . In other words, comments are notes for humans, not instructions for machines. They help developers explain the purpose of code, describe logic, or temporarily disable certain lines of code without deleting them. Why are Comments Important? ๐Ÿ“Œ Readability – Comments make code easier to understand for you and others. ๐Ÿ“Œ Maintenance – When you revisit your code after months, comments remind you what you were doing. ๐Ÿ“Œ Collaboration – In team projects, comments explain code to fellow developers. ๐Ÿ“Œ Debugging – You c...

Java Program to Check Voting Eligibility

In this program, we’ll take the user’s age as input and check whether the person is eligible to vote or not. In India, the minimum age required to vote is 18 years . ๐Ÿ’ป Program Code // Java Program to Check Voting Eligibility import java.util.Scanner; public class VotingEligibility { public static void main(String[] args) { // Create Scanner object to take input from user Scanner sc = new Scanner(System.in); // Ask user to enter age System.out.print("Enter your age: "); int age = sc.nextInt(); // Check eligibility if (age >= 18) { System.out.println("You are eligible to vote."); } else { System.out.println("You are not eligible to vote yet."); System.out.println("You can vote after " + (18 - age) + " year(s)."); } sc.close(); // Close the scanner } } ๐Ÿง  Explanation import java.util.Scanner; → Imp...

Java Program to Calculate Total Marks and Average of Five Subjects

๐Ÿ’ก Program Explanation In this program: The user will input marks of five subjects . The program will calculate the total marks and average . It will then display both results clearly. ๐Ÿง‘‍๐Ÿ’ป Java Code: // Java Program to Calculate Total Marks and Average of Five Subjects import java.util.Scanner; // Importing Scanner class for user input public class TotalAndAverage { public static void main(String[] args) { // Creating Scanner object to take input from user Scanner sc = new Scanner(System.in); // Declaring variables for five subjects double subject1, subject2, subject3, subject4, subject5; // Taking marks input for each subject System.out.print("Enter marks of Subject 1: "); subject1 = sc.nextDouble(); System.out.print("Enter marks of Subject 2: "); subject2 = sc.nextDouble(); System.out.print("Enter marks of Subject 3: "); subject3 = sc.nextDo...