Using JSON in APIs - potatoscript/json GitHub Wiki
π Using JSON in APIs: Mastering Data Communication! π
Welcome to the Magic World of APIs and JSON! π
APIs (Application Programming Interfaces) are like bridges π that allow different systems to talk to each other.
And guess what? JSON is the language they use to communicate! π£οΈπ‘
π― What is an API and How Does JSON Fit In?
-
API (Application Programming Interface):
An API allows different applications or services to send and receive data.
β‘οΈ Think of it like a waiter taking orders (requests) and bringing food (responses). ππ§Ύ -
JSON (JavaScript Object Notation):
APIs use JSON to format and exchange data between servers and clients.
β‘οΈ Itβs like the language that both the client and the server understand. ππ
πΉοΈ 1. Basic API Workflow with JSON
- π¨ Client (Browser/App): Sends a request to the server (usually via HTTP/HTTPS).
- π‘ Server (Backend): Processes the request and sends back a response in JSON format.
- π© Client: Parses and uses the JSON data.
π― Example: Basic API Request/Response Flow
Client: "Hey API, give me the user data!"
Server:
{
"name": "Lucy",
"age": 25,
"hobbies": ["reading", "coding", "traveling"]
}
Client: "Got it! Thanks!"
β Explanation:
- The client sends a request to the server.
- The server responds with a JSON object containing user data.
π 2. Sending JSON with API Requests (POST/PUT) π
When you want to send data to an API, you encode the data into JSON format using JSON.stringify()
and send it with a POST or PUT request.
π― Example: Sending JSON with POST Request
let user = {
name: "Lucy",
age: 25,
hobbies: ["reading", "coding"]
};
// Send data to API
fetch("https://api.example.com/users", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(user)
})
.then(response => response.json())
.then(data => console.log("User added:", data))
.catch(error => console.error("Error:", error));
β Explanation:
fetch()
sends a POST request tohttps://api.example.com/users
.body: JSON.stringify(user)
converts the object to a JSON string.- The server processes the data and returns a JSON response.
π― Example: Updating Data with PUT Request
let updatedUser = {
name: "Lucy Berry",
age: 26
};
// Update data on server
fetch("https://api.example.com/users/123", {
method: "PUT",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(updatedUser)
})
.then(response => response.json())
.then(data => console.log("User updated:", data))
.catch(error => console.error("Error:", error));
β Explanation:
PUT
updates an existing user at/users/123
.- The server responds with the updated data.
π© 3. Receiving and Parsing JSON from APIs (GET) π‘
When you retrieve data from an API, the response is usually in JSON format.
You use JSON.parse()
to convert it into a JavaScript object.
π― Example: Fetching Data with GET Request
// Fetch data from API
fetch("https://api.example.com/users/123")
.then(response => {
if (!response.ok) {
throw new Error("Network response was not ok");
}
return response.json();
})
.then(data => {
console.log("User data:", data);
console.log("Name:", data.name);
console.log("Age:", data.age);
})
.catch(error => console.error("Error fetching data:", error));
β Explanation:
fetch()
sends a GET request to retrieve user data.response.json()
parses the JSON response into a JavaScript object.- You can access the objectβs properties easily. π
π₯ 4. Common API Methods with JSON
π HTTP Method | π Action | π Description |
---|---|---|
GET |
Read/Retrieve Data | Fetch data from the server. |
POST |
Create Data | Add new data to the server. |
PUT |
Update/Replace Data | Update existing data completely. |
PATCH |
Modify/Partially Update Data | Update specific parts of data. |
DELETE |
Remove Data | Delete data from the server. |
π§© 5. Handling API Errors Gracefully! π
APIs donβt always behave as expected!
You should handle errors carefully using try...catch
or .catch()
. π‘οΈ
π― Example: Error Handling with Fetch
// API with error handling
fetch("https://api.example.com/users/999")
.then(response => {
if (!response.ok) {
throw new Error(`Error: ${response.status} - ${response.statusText}`);
}
return response.json();
})
.then(data => console.log("User data:", data))
.catch(error => console.error("Failed to fetch data:", error.message));
β Explanation:
- Check
response.ok
to confirm the request succeeded. - Handle errors gracefully using
.catch()
orthrow new Error()
.
π‘ 6. Sending Headers with API Requests
Headers provide extra information to APIs, such as authentication tokens or content types.
π― Example: Sending Custom Headers
let userData = {
name: "Lucy",
age: 25
};
// Send data with custom headers
fetch("https://api.example.com/users", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer my-secret-token"
},
body: JSON.stringify(userData)
})
.then(response => response.json())
.then(data => console.log("User added:", data))
.catch(error => console.error("Error:", error));
β Explanation:
Content-Type
tells the server the data format.Authorization
is used for sending API tokens for authentication. π
πΉοΈ 7. Sending Query Parameters in API Requests
You can add query parameters to a URL to send additional data with a GET
request. π
π― Example: Sending Query Parameters
let userId = 123;
let url = `https://api.example.com/users?userId=${userId}`;
// Fetch data with query parameter
fetch(url)
.then(response => response.json())
.then(data => console.log("User data:", data))
.catch(error => console.error("Error:", error));
β Explanation:
?userId=123
adds query parameters to the URL.- APIs can read these parameters and return filtered data.
π¦ 8. Handling JSON Arrays from APIs
APIs often return arrays of objects. You can loop through them to extract and display data. π
π― Example: Fetching and Looping Through JSON Array
// Fetch data from API
fetch("https://api.example.com/users")
.then(response => response.json())
.then(users => {
users.forEach(user => {
console.log(`Name: ${user.name}, Age: ${user.age}`);
});
})
.catch(error => console.error("Error fetching data:", error));
β Explanation:
users
is an array returned by the API.forEach()
loops through each object and displays the data.
π§ 9. JSON and RESTful APIs: The Perfect Duo!
APIs that follow the RESTful architecture use standard HTTP methods (GET
, POST
, etc.)
They communicate using JSON for data exchange. π
π― Example: RESTful API Endpoints
GET /users -> Fetch all users
GET /users/123 -> Fetch user with ID 123
POST /users -> Add a new user
PUT /users/123 -> Update user with ID 123
DELETE /users/123 -> Delete user with ID 123
β Explanation:
- RESTful APIs organize data into resources (
/users
,/products
). - JSON is the standard format for sending and receiving data. π‘
π οΈ 10. Real-World Use Cases of JSON in APIs
β
User Authentication: Login, token exchange, and user sessions. π
β
E-Commerce Apps: Fetching product listings, adding to cart, and payments. π
β
Weather Forecasts: Retrieving live weather data based on location. βοΈπ§οΈ
β
Social Media Platforms: Fetching user profiles, posts, and comments. πΈ