JavaScript · API · Beginner
Your First Request
Make your first HTTP request with fetch and read the JSON response.
Quick topic start and explanations before exercises (exercises below):
Reading the response
#fetch and Response quick reference
#Exercises:
Fetch the product list
#const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
// 1. fetch /api/products/
// 2. print count and results.length
}
main();
Solution
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
const response = await fetch(`${BASE_URL}/api/products/`);
const data = await response.json();
console.log(data.count);
console.log(data.results.length);
}
main();
Fetch a single product
#const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
// GET /api/products/1/
// print name, price, slug
}
main();
Solution
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
const response = await fetch(`${BASE_URL}/api/products/1/`);
const product = await response.json();
console.log(product.name);
console.log(product.price);
console.log(product.slug);
}
main();
Check response.status and response.ok
#const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
// Fetch a missing product — check status and ok
// Fetch a real product — check status and ok
}
main();
Solution
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
const r1 = await fetch(`${BASE_URL}/api/products/99999/`);
console.log(r1.status, r1.ok); // 404 false
const r2 = await fetch(`${BASE_URL}/api/products/1/`);
console.log(r2.status, r2.ok); // 200 true
}
main();
Fetch categories
#const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
// GET /api/categories/ and print count + each name
}
main();
Solution
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
const response = await fetch(`${BASE_URL}/api/categories/`);
const data = await response.json();
console.log(data.count);
for (const cat of data.results) {
console.log(cat.name);
}
}
main();
Fetch the first product name from the list
#const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
// fetch products, get first result, print name, price string, and parsed price
}
main();
Solution
const BASE_URL = 'https://apilearn.tukas.dev';
async function main() {
const response = await fetch(`${BASE_URL}/api/products/`);
const data = await response.json();
const first = data.results[0];
console.log(first.name);
console.log(first.price);
console.log(parseFloat(first.price));
}
main();