Lesson 15, Thursday, 2024-11-14
- Recap
- JavaScript Object Notation (JSON)
fetch
API
What appears on the web page after this code runs?
let el = document.createElement("button");
el.textContent = "Click me!";
Answer: Nothing, because we never append the element anywhere
Corrected code:
let el = document.createElement("button");
el.textContent = "Click me!";
document.body.appendChild(el);
Now, the button is appended to the body. It'll appear after all other elements.
In JavaScript, we can put all keys of objects in quotes. This is purely optional. We can still access the keys without quotes:
let me = {
"name": "John",
"lastName": "Doe",
"hobbies": ["Eat", "Sleep"],
};
console.log(me.name); // "John"
Let's say we want to transfer the object me
over the internet. We can't just send the object, because the internet only understands strings.
We could send a string like "Hi my name is John Doe and I like to eat and sleep". But then how would the receiver know what is the name, what is the last name, and what are the hobbies?
- JSON stands for JavaScript Object Notation
- When we exchange data between a browser and a server, we can only exchange string (not objects, arrays, numbers, booleans...)
- JSON is a string representation of JavaScript objects
- JSON can be easily transferred (and stored)
- The notation is very close to JavaScript objects, easy to handle from JavaScript. No complex transformation required.
- More info: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/JSON
- All keys in our key value pairs must be in quotes
- Must contain only these types:
string
,number
,boolean
,array
null
- another JSON
object
- These types are forbidden:
function
,undefined
{
"name": "Alan",
"instructor": true,
"hobbies": ["bike", "jog"],
"age": 42,
"workAddress": {
"street": "Invalidenstraße",
"number": 116,
"city": "Berlin"
},
"profilePicture": null
}
There are a lot of services on the internet that transfer data via JSON.
Example: https://restcountries.com/v3.1/lang/spanish Documentation: https://restcountries.com/
Find more at https://apilist.fun, https://rapidapi.com/hub or https://apis.guru
OK great, but how can we access that from JavaScript?
- Fetching data from the internet might take a lot of time
- We must not block our browser while waiting for the reply!
Let's say I want you to do something for me. I'll give you a promise that I'll give you one cookie when you're done. You can do whatever you want with the money, but you can't have it until you're done.
Now, I can watch you do the work, and when you're done, I'll give you the cookie. Or, I can go do something else, and when you're done, you call me and I'll give you the cookie.
We call the first method "synchronous", and the second method "asynchronous". "synchronous" means "at the same time", "asynchronous" means "not at the same time". "synchronous" code must wait for the result, "asynchronous" code can continue running other code.
function add(a, b) {
return a + b;
}
let result = add(1, 2);
add(1, 2)
is a synchronous function call. The function is called, and the result is returned immediately. No other code runs in between. While add
runs, the entire web page is blocked.
async function add(a, b) {
return a + b;
}
let result = add(1, 2);
We define add
with the additional async
keyword. This tells JavaScript that the function is asynchronous. The function is called, but the result is not returned immediately. The function returns a promise.
So great, we can call a function asynchronously.
But how do we get the result?
async function add(a, b) {
return a + b;
}
async function main() {
let result = await add(1, 2);
}
main();
We can use the await
keyword to wait for the result of an asynchronous function. The await
keyword can only be used inside an async
function.
fetch
is an async
function that we can use to download content from the internet asynchronously:
async function main() {
let response = await fetch("https://restcountries.com/v3.1/lang/spanish");
let data = await response.json();
console.log(data);
}
- Download the data from https://restcountries.com/v3.1/name/deutschland (or any country you like) in JavaScript and log the response to console
- Create a web page that displays the country's official name, its area and its population
- Bonus: Show the capital cities
- Bonus: Display the flag and the coat of arms of the country as SVG file. (Hint: use
img
element and set thesrc
attribute).
- Add an input field and a button to your page. When the user clicks the button, show the details about the country that the user entered in the input field.
- Sometimes, more than one country can be returned. Try entering "united" in your input field. Extend your web page to show all countries that match the user's input.
- Show all the bordering countries (field:
borders
) as buttons. Example: Germany has a neighbour calledAUT
. Create a button with text contentAUT
and when the user clicks the button, the page should display information about this country (hint: use thealpha
API, e.g: https://restcountries.com/v3.1/alpha/aut)
https://dog.ceo/dog-api/documentation/random
Display a random dog image
https://kinduff.github.io/dog-api/
Fetch dog facts
Create a simple webpage, that fetches dog images from the API. Pair it with the second API and show some dog facts together with images.
Query the holidays of over 100 countries
Show the holidays in Germany for 2024.
BONUS: Add a dropdown to select holidays for one state only.