Assignments Of Day 17: Working with APIs in JavaScript
Assignment
1: Basic API Fetch Request
Problem:
Make a
GET request to the following API: https://jsonplaceholder.typicode.com/posts.
Log the response to the console.
Solution:
javascript
Copy code
fetch('https://jsonplaceholder.typicode.com/posts') // Step 1: Make a GET request
.then(response => response.json())
// Step 2: Parse the response as JSON
.then(data
=> console.log(data)) // Step 3: Log
the parsed data
.catch(error => console.error('Error:', error)); // Step 4: Handle any errors
Explanation:
1. fetch(): Sends a
GET request to the provided URL.
2. response.json():
Converts the raw response into JSON format.
3. console.log(): Outputs
the parsed data to the console.
4. .catch(): Catches
any error (e.g., network failure) and logs it.
Assignment
2: Handling Errors in Fetch Requests
Problem:
Modify
the previous code to check if the response status is OK (i.e., status code
200-299). If the response is not OK, throw an error with the message
"Failed to fetch data". Handle errors properly.
Solution:
javascript
Copy code
fetch('https://jsonplaceholder.typicode.com/posts') // Step 1: Make a GET request
.then(response => {
if
(!response.ok) {
throw
new Error('Failed to fetch data'); //
Step 2: Throw error if not OK
}
return
response.json(); // Step 3: Parse the
response as JSON
})
.then(data
=> console.log(data)) // Step 4: Log
the data
.catch(error => console.error('Error:', error.message)); // Step 5: Catch and log any errors
Explanation:
1. We use
response.ok to check if the status code of the response is between 200 and 299.
2. If the
status is not OK, we throw an error.
3. If the
response is OK, we parse the data as JSON and log it.
4. Any
errors encountered will be caught and logged in the .catch() block.
Assignment
3: POST Request to Create New Data
Problem:
Send a
POST request to the API endpoint https://jsonplaceholder.typicode.com/posts
with a new post object:
javascript
Copy code
{
title:
"New Post",
body:
"This is the body of the new post.",
userId: 1
}
Log the
response received after sending the data.
Solution:
javascript
Copy code
fetch('https://jsonplaceholder.typicode.com/posts',
{
method:
'POST', // Step 1: Specify the HTTP
method as POST
headers: {
'Content-Type': 'application/json',
// Step 2: Set content type to JSON
},
body:
JSON.stringify({
title:
'New Post',
body:
'This is the body of the new post.',
userId: 1
}) // Step 3: Convert the JavaScript object to
JSON
})
.then(response => response.json())
// Step 4: Parse the response as JSON
.then(data
=> console.log('Data posted:', data))
// Step 5: Log the response data
.catch(error => console.error('Error:', error)); // Step 6: Handle any errors
Explanation:
1. method:
'POST': Specifies that the request will be a POST request, used to send data
to the server.
2. headers:
Specifies the type of data being sent (in this case, JSON).
3. body: We
stringify a JavaScript object to send as the request body.
4. response.json(): The
server responds with JSON, so we parse it.
5. The
response is logged using console.log().
Assignment
4: Delete Data Using DELETE Request
Problem:
Send a
DELETE request to the API endpoint https://jsonplaceholder.typicode.com/posts/1
to delete the post with ID 1. Log a success message if the deletion is
successful.
Solution:
javascript
Copy code
fetch('https://jsonplaceholder.typicode.com/posts/1',
{
method:
'DELETE' // Step 1: Specify the HTTP
method as DELETE
})
.then(response => {
if
(response.ok) { // Step 2: Check if the
response is successful
console.log('Post deleted'); //
Step 3: Log success message
} else {
console.log('Failed to delete post');
// Step 4: Log failure message
}
})
.catch(error => console.error('Error:', error)); // Step 5: Catch any errors
Explanation:
1. method:
'DELETE': Specifies the HTTP method as DELETE to remove data from the server.
2. If the
response is OK (response.ok), it logs that the post was deleted.
3. If the
response is not OK, it logs a failure message.
Assignment
5: Handling JSON Response and Displaying Data
Problem:
Make a
GET request to https://jsonplaceholder.typicode.com/users. For each user,
display their name, email, and address in the following format:
makefile
Copy code
Name: [User Name]
Email: [User Email]
Address: [User Address]
Solution:
javascript
Copy code
fetch('https://jsonplaceholder.typicode.com/users') // Step 1: Make a GET request
.then(response => response.json())
// Step 2: Parse the response as JSON
.then(users
=> {
users.forEach(user => { //
Step 3: Loop through each user in the array
console.log(`Name: ${user.name}`);
// Step 4: Log user name
console.log(`Email: ${user.email}`);
// Step 5: Log user email
console.log(`Address: ${user.address.street},
${user.address.city}`); // Step 6: Log
user address
console.log('---');
});
})
.catch(error => console.error('Error:', error)); // Step 7: Handle any errors
Explanation:
1. fetch('https://jsonplaceholder.typicode.com/users'): Sends a
GET request to fetch the list of users.
2. .then(response
=> response.json()): Parses the response as JSON.
3. We loop
through the array of users using .forEach().
4. We use
template literals to log the user’s name, email, and address.
5. .catch(): Catches
and logs any errors.
Assignment
6: Display Error Message for Failed Fetch
Problem:
Make a
GET request to a non-existent endpoint (https://jsonplaceholder.typicode.com/invalidendpoint).
Display a message saying "Unable to fetch data from the API" when an
error occurs.
Solution:
javascript
Copy code
fetch('https://jsonplaceholder.typicode.com/invalidendpoint') // Step 1: Make a GET request to an invalid
endpoint
.then(response => {
if
(!response.ok) { // Step 2: Check if
response is OK
throw
new Error('Unable to fetch data from the API');
// Step 3: Throw error if not OK
}
return
response.json(); // Step 4: Parse the
response as JSON
})
.then(data
=> console.log(data)) // Step 5: Log
the data (won't be reached if error occurs)
.catch(error => console.error(error.message)); // Step 6: Log error message
Explanation:
1. We try to
make a GET request to a non-existent endpoint.
2. Since the
request fails, we throw an error with the custom message.
3. We catch
the error and display the message "Unable to fetch data from the
API".
These
assignments cover basic interactions with APIs, including handling errors,
sending data, and parsing JSON responses. They provide hands-on experience with
working with APIs in JavaScript.
4o mini
You said:
more
ChatGPT
said:
ChatGPT
Here are
more assignments to help you understand API handling in JavaScript better:
Assignment
7: PUT Request to Update Data
Problem:
Send a
PUT request to update the post with ID 1 at the API endpoint
https://jsonplaceholder.typicode.com/posts/1. Update the post’s title, body,
and userId to new values and log the updated post.
Solution:
javascript
Copy code
fetch('https://jsonplaceholder.typicode.com/posts/1',
{
method:
'PUT', // Step 1: Specify the HTTP
method as PUT
headers: {
'Content-Type': 'application/json',
// Step 2: Set content type to JSON
},
body:
JSON.stringify({ // Step 3: Send updated
data as JSON
title:
'Updated Post Title',
body:
'This is the updated body of the post.',
userId: 1
})
})
.then(response => response.json())
// Step 4: Parse the response as JSON
.then(updatedPost => console.log('Updated Post:', updatedPost)) // Step 5: Log the updated post data
.catch(error => console.error('Error:', error)); // Step 6: Handle any errors
Explanation:
1. method:
'PUT': The PUT method is used to update an existing resource on the server.
2. headers: We
specify that the data we are sending is JSON.
3. body: We send
the updated data in JSON format.
4. response.json(): We
parse the JSON response from the server and log the updated post.
Assignment
8: Handling API Response Status Codes
Problem:
Make a
GET request to https://jsonplaceholder.typicode.com/posts/1000 (a post that
doesn’t exist). Check the response status code. If the status code is 404,
display the message "Post not found", otherwise display the data.
Solution:
javascript
Copy code
fetch('https://jsonplaceholder.typicode.com/posts/1000') // Step 1: Make a GET request
.then(response => {
if
(response.status === 404) { // Step 2:
Check if status is 404 (Not Found)
console.log('Post not found');
} else {
return
response.json(); // Step 3: Parse the
response as JSON if not 404
}
})
.then(data
=> {
if (data)
{
console.log('Post Data:', data);
// Step 4: Log the data if it exists
}
})
.catch(error => console.error('Error:', error)); // Step 5: Handle any errors
Explanation:
1. response.status: We
check if the response status code is 404 (Not Found).
2. If the
status is 404, we log "Post not found".
3. Otherwise,
we parse the response as JSON and log the data.
4. Any
errors are handled using .catch().
Assignment
9: Display Data from Multiple API Endpoints
Problem:
Make
multiple API requests to https://jsonplaceholder.typicode.com/users and https://jsonplaceholder.typicode.com/posts.
Display the user names and their corresponding posts (by userId) on the page.
Solution:
javascript
Copy code
// Fetch users and posts concurrently using
Promise.all
Promise.all([
fetch('https://jsonplaceholder.typicode.com/users').then(response =>
response.json()),
fetch('https://jsonplaceholder.typicode.com/posts').then(response =>
response.json())
])
.then(([users, posts]) => { //
Step 1: Destructure the resolved promises
users.forEach(user => {
console.log(`User: ${user.name}`);
// Step 2: Log the user name
const
userPosts = posts.filter(post => post.userId === user.id); // Step 3: Find posts by the user
userPosts.forEach(post => {
console.log(`Post: ${post.title}`);
// Step 4: Log post titles
});
});
})
.catch(error => console.error('Error:', error)); // Step 5: Handle errors
Explanation:
1. Promise.all(): Used to
handle multiple fetch requests concurrently.
2. Once both
promises resolve, we destructure the results (users and posts).
3. We loop
through the users array, and for each user, we filter the posts array to find
posts written by that user.
4. We log the
user’s name and their corresponding posts.
Assignment
10: API Data and Dynamic HTML Display
Problem:
Make a
GET request to https://jsonplaceholder.typicode.com/users and display the
users' names and email addresses in a table format on the webpage.
Solution:
javascript
Copy code
// Fetch users and display them in a table
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json())
// Step 1: Parse the response as JSON
.then(users
=> {
const
table = document.createElement('table');
// Step 2: Create a new table element
const
header = document.createElement('tr');
// Step 3: Create a table header
header.innerHTML =
'<th>Name</th><th>Email</th>'; // Step 4: Set table headers
table.appendChild(header); //
Step 5: Append header to table
users.forEach(user => {
const
row = document.createElement('tr'); //
Step 6: Create a row for each user
row.innerHTML =
`<td>${user.name}</td><td>${user.email}</td>`; // Step 7: Add user data to row
table.appendChild(row); // Step
8: Append row to table
});
document.body.appendChild(table);
// Step 9: Append the table to the webpage
})
.catch(error => console.error('Error:', error)); // Step 10: Handle errors
Explanation:
1. fetch(): We send
a GET request to fetch users.
2. We create
a table dynamically using document.createElement() and set up headers.
3. For each
user, a row is created and appended to the table.
4. The table
is then appended to the body of the webpage, displaying the users' names and
emails.
Assignment
11: Using async/await with API Requests
Problem:
Refactor
the previous example (Assignment 10) using async and await syntax to handle the
fetch requests.
Solution:
javascript
Copy code
async function fetchAndDisplayUsers() {
try {
const
response = await fetch('https://jsonplaceholder.typicode.com/users'); // Step 1: Wait for the fetch request to
complete
const
users = await response.json(); // Step
2: Wait for the response to be parsed as JSON
const
table = document.createElement('table');
// Step 3: Create a table element
const
header = document.createElement('tr');
// Step 4: Create table header
header.innerHTML =
'<th>Name</th><th>Email</th>';
table.appendChild(header);
users.forEach(user => {
const
row = document.createElement('tr');
row.innerHTML =
`<td>${user.name}</td><td>${user.email}</td>`;
table.appendChild(row);
});
document.body.appendChild(table);
// Step 5: Append the table to the webpage
} catch
(error) {
console.error('Error:', error);
// Step 6: Handle any errors
}
}
fetchAndDisplayUsers(); // Step 7: Call the function to fetch and
display users
Explanation:
1. async/await: The
fetchAndDisplayUsers function is declared as async. This allows us to use await
to pause execution until the fetch request and JSON parsing are completed.
2. The rest
of the logic remains similar to the previous assignment, but now we use await
for asynchronous operations.
