Practice and reinforce the concepts from Lesson 2
By the end of this activity, you will:
Access the template here: Pokemon JSON Parser Template
git clone
and navigate to the template folderindex.html
in your browser to start!The template includes:
Choose the API theme that interests you most:
Option A: Professional Practice (Recommended for beginners)
Option B: Pop Culture & Fun
Option C: Creative & Random
Fetch single item data and display key information.
async function fetchUser() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/users/1');
const data = await response.json();
document.getElementById('result').innerHTML = `
<h3>User: ${data.name}</h3>
<p>Email: ${data.email}</p>
<p>Company: ${data.company.name}</p>
`;
} catch (error) {
console.error('Error fetching user:', error);
}
}
async function fetchPokemon() {
try {
const response = await fetch('https://pokeapi.co/api/v2/pokemon/pikachu');
const data = await response.json();
document.getElementById('result').innerHTML = `
<h3>Pokemon: ${data.name}</h3>
<p>Height: ${data.height} | Weight: ${data.weight}</p>
<p>Type: ${data.types[0].type.name}</p>
<img src="${data.sprites.front_default}" alt="${data.name}">
`;
} catch (error) {
console.error('Error fetching Pokemon:', error);
}
}
async function fetchCharacter() {
try {
const response = await fetch('https://swapi.dev/api/people/1');
const data = await response.json();
document.getElementById('result').innerHTML = `
<h3>Character: ${data.name}</h3>
<p>Height: ${data.height}cm</p>
<p>Hair: ${data.hair_color}</p>
<p>Birth Year: ${data.birth_year}</p>
`;
} catch (error) {
console.error('Error fetching character:', error);
}
}
Pick one API path and implement the function. Focus on:
Fetch multiple items and display them as a formatted list.
async function fetchUserPosts() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts?userId=1');
const posts = await response.json();
const first3Posts = posts.slice(0, 3);
let html = '<h3>User Posts:</h3>';
first3Posts.forEach((post, index) => {
html += `
<div>
<h4>${index + 1}. ${post.title}</h4>
<p>${post.body.substring(0, 100)}...</p>
</div>
`;
});
document.getElementById('result').innerHTML = html;
} catch (error) {
console.error('Error fetching posts:', error);
}
}
async function fetchPokemonTeam() {
try {
const pokemonNames = ['pikachu', 'charmander', 'squirtle'];
const promises = pokemonNames.map(name =>
fetch(`https://pokeapi.co/api/v2/pokemon/${name}`).then(r => r.json())
);
const pokemonData = await Promise.all(promises);
let html = '<h3>Pokemon Team:</h3>';
pokemonData.forEach(pokemon => {
html += `
<div style="border: 1px solid #ccc; margin: 10px; padding: 10px;">
<h4>${pokemon.name}</h4>
<img src="${pokemon.sprites.front_default}" alt="${pokemon.name}">
<p>Type: ${pokemon.types[0].type.name}</p>
</div>
`;
});
document.getElementById('result').innerHTML = html;
} catch (error) {
console.error('Error fetching Pokemon team:', error);
}
}
async function fetchCharacters() {
try {
const response = await fetch('https://swapi.dev/api/people/');
const data = await response.json();
const first3Characters = data.results.slice(0, 3);
let html = '<h3>Star Wars Characters:</h3>';
first3Characters.forEach((character, index) => {
html += `
<div>
<h4>${index + 1}. ${character.name}</h4>
<p>Height: ${character.height}cm | Hair: ${character.hair_color}</p>
<p>Birth Year: ${character.birth_year}</p>
</div>
`;
});
document.getElementById('result').innerHTML = html;
} catch (error) {
console.error('Error fetching characters:', error);
}
}
slice()
to limit resultsCreate a search function that handles user input and errors gracefully.
async function searchUser() {
const userId = document.getElementById('searchInput').value;
if (!userId || userId < 1 || userId > 10) {
document.getElementById('result').innerHTML = '<p style="color: red;">Please enter a user ID between 1-10</p>';
return;
}
try {
document.getElementById('result').innerHTML = '<p>Loading user...</p>';
const response = await fetch(`https://jsonplaceholder.typicode.com/users/${userId}`);
if (!response.ok) {
throw new Error('User not found');
}
const user = await response.json();
document.getElementById('result').innerHTML = `
<h3>User Found!</h3>
<p><strong>Name:</strong> ${user.name}</p>
<p><strong>Email:</strong> ${user.email}</p>
<p><strong>Phone:</strong> ${user.phone}</p>
<p><strong>Company:</strong> ${user.company.name}</p>
`;
} catch (error) {
document.getElementById('result').innerHTML = `<p style="color: red;">Error: ${error.message}</p>`;
}
}
async function searchPokemon() {
const pokemonName = document.getElementById('searchInput').value.toLowerCase().trim();
if (!pokemonName) {
document.getElementById('result').innerHTML = '<p style="color: red;">Please enter a Pokemon name</p>';
return;
}
try {
document.getElementById('result').innerHTML = '<p>Searching for Pokemon...</p>';
const response = await fetch(`https://pokeapi.co/api/v2/pokemon/${pokemonName}`);
if (!response.ok) {
throw new Error('Pokemon not found');
}
const pokemon = await response.json();
document.getElementById('result').innerHTML = `
<h3>Pokemon Found!</h3>
<img src="${pokemon.sprites.front_default}" alt="${pokemon.name}">
<p><strong>Name:</strong> ${pokemon.name}</p>
<p><strong>Height:</strong> ${pokemon.height}</p>
<p><strong>Weight:</strong> ${pokemon.weight}</p>
<p><strong>Type:</strong> ${pokemon.types.map(t => t.type.name).join(', ')}</p>
`;
} catch (error) {
document.getElementById('result').innerHTML = `<p style="color: red;">Error: ${error.message}</p>`;
}
}
async function searchCharacter() {
const query = document.getElementById('searchInput').value.trim();
if (!query) {
document.getElementById('result').innerHTML = '<p style="color: red;">Please enter a character name</p>';
return;
}
try {
document.getElementById('result').innerHTML = '<p>Searching galaxy...</p>';
const response = await fetch(`https://swapi.dev/api/people/?search=${query}`);
const data = await response.json();
if (data.results.length === 0) {
throw new Error('Character not found in a galaxy far, far away...');
}
const character = data.results[0];
document.getElementById('result').innerHTML = `
<h3>Character Found!</h3>
<p><strong>Name:</strong> ${character.name}</p>
<p><strong>Height:</strong> ${character.height}cm</p>
<p><strong>Hair Color:</strong> ${character.hair_color}</p>
<p><strong>Birth Year:</strong> ${character.birth_year}</p>
`;
} catch (error) {
document.getElementById('result').innerHTML = `<p style="color: red;">Error: ${error.message}</p>`;
}
}
// Response is automatically parsed with .json()
const data = await response.json();
async function fetchData() {
try {
const response = await fetch(url);
const data = await response.json();
return data;
} catch (error) {
console.error('Error:', error);
}
}
Ready for more? Try these additional challenges:
In the next activity, we'll apply these JSON and fetch skills to build the first version of our Weather Dashboard, connecting to a real weather API and handling more complex data structures.
💡 Pro Tip: JSONPlaceholder is perfect for learning, but real APIs often have authentication and rate limits. Always read the API documentation before integrating into production applications!