By the end of this lesson, you will be able to:
:information_source: What is an API? An Application Programming Interface (API) is like a waiter in a restaurant. Just as a waiter takes your order to the kitchen and brings back your food, an API takes requests from one application to another and brings back the data you need.
APIs let us access data and features from other applications. Think of them as bridges that connect different apps together!
APIs speak in a special language called JSON. Let's learn how to read it!
:memo: Note JSON stands for JavaScript Object Notation. It's a simple way to organize and send data as text.
When your browser talks to a server, they can only exchange text messages. JSON helps organize this text so both sides understand what the data means.
JSON follows three simple rules:
Here's what JSON looks like:
An API endpoint is like a website address (URL) where you can request data. It's the front door to the API!
Think of endpoints like addresses:
Most endpoints follow this pattern:
Let's explore a real API endpoint: https://www.boredapi.com/api/
When you visit this endpoint, you see:
{"message": "Bored API"}
This is like knocking on the front door - the API says "Hello, I'm the Bored API!" But to get actual data, you need to ask for something specific using an API path.
API paths tell the API exactly what data you want. They're like asking for a specific item from a menu!
To get data, you combine:
Example: https://www.boredapi.com/api/activity
https://www.boredapi.com/api/
/activity
When you visit this complete URL, you get:
{
"activity": "Host a movie marathon with some friends",
"type": "social",
"participants": 3,
"price": 0.1,
"link": "",
"key": "5914292",
"accessibility": 0
}
:bulb: Tip The path
/activity
tells the Bored API: "Give me a random activity to do!"
Let's explore some real APIs! We'll use a tool called Hoppscotch to see API responses clearly.
:memo: Note Troubleshooting: If you see an error, select "Proxy" as the interceptor in settings.
Try these APIs in Hoppscotch:
Cat Facts: https://catfact.ninja/fact
Get random facts about cats!
Cat Status Codes: https://http.cat/
See HTTP status codes explained with cat pictures
Makeup Products: https://makeup-api.herokuapp.com/api/v1/products.json
Browse makeup product information
Yes or No: https://yesno.wtf/api
Get random yes/no answers with GIFs
Weather API: https://goweather.herokuapp.com/weather/KL
Check weather for different cities (Documentation)
Fruits Database: https://www.fruityvice.com/api/fruit/all
Learn nutrition facts about fruits
Pokemon API: https://pokeapi.co/api/v2/pokemon/
Get data about all Pokemon
JavaScript has special functions called async functions that handle tasks that take time - like waiting for API data!
async function getData() {
// fetch data here
}
Imagine you order pizza:
That's exactly how async functions work! Your code keeps running other tasks while waiting for API data.
:bulb: Tip The word "async" is short for "asynchronous" - which means "not at the same time". Your code doesn't freeze while waiting!
The fetch()
function is how we grab data from APIs. Let's see it in action!
Here's how to fetch cat facts from an API:
let catFact;
async function getCatFact() {
fetch("https://catfact.ninja/fact")
.then((response) => response.json())
.then((data) => {
catFact = data.fact; // JSON Path for the cat fact
});
}
When the Cat Facts API responds, it sends this JSON:
{
"fact": "The oldest cat on record was Crème Puff from Austin, Texas, who lived from 1967 to August 6, 2005, three days after her 38th birthday. A cat typically can live up to 20 years, which is equivalent to about 96 human years.",
"length": 220
}
The JSON contains:
So we use data.fact
to get just the fact:
catFact = data.fact; // Gets only the fact, ignores the length
:memo: Note Pro tip: Use Hoppscotch to explore API responses and find the exact path to the data you need!
Now let's make our APIs interactive! Users can input what they want to search for.
For basic APIs like Cat Facts, a simple button works:
<button on:click={getCatFact}>Get Cat Fact</button>
Many APIs let you customize your request. The Bored API lets you choose activity types:
https://www.boredapi.com/api/activity
https://www.boredapi.com/api/activity?type=education
Available types: education, recreational, social, diy, charity, cooking, relaxation, music, busywork
<script>
let activity = "";
let type = "";
async function getBoredActivity() {
fetch('https://www.boredapi.com/api/activity?type=' + type)
.then((response) => response.json())
.then((data) => {
activity = data.activity; // Path for activity
type = data.type; // Path for type
});
}
</script>
<form on:submit|preventDefault={getBoredActivity}>
<label for="type">Type:</label>
<input id="type" bind:value={type} type="text" />
<button type="submit">Get random activity</button>
</form>
<p>Activity: {activity}</p>
<p>Type: {type}</p>
:bulb: Tip Try it yourself! Copy this code to Svelte REPL and experiment with different activity types!
Let's review what we learned about APIs!
Watch these videos to see APIs in action:
Remember: APIs are everywhere on the internet - from weather apps to social media. Now you know how they work!