Interacting with APIs
Learning objectives
- You know how to interact with APIs in Svelte.
When building Svelte applications, we are building client-side functionality. This means that we can leverage all the APIs that browsers come with, including the Fetch API. It is the same API that we used when we learned to use external APIs with Deno. In brief, the Fetch API allows us to make HTTP requests to servers, which lead to responses, which we can then parse.
To illustrate this, create a new Svelte component called Dog.svelte
and place the following content to the the file.
<script>
let dog = $state("https://images.dog.ceo/breeds/pekinese/n02086079_10721.jpg");
const fetchRandomDog = async () => {
const response = await fetch("https://dog.ceo/api/breeds/image/random");
const data = await response.json();
dog = data.message;
};
</script>
<button on:click={fetchRandomDog}>Fetch new dog</button>
<br/>
<img src={dog} alt="A dog" />
The above component provides the functionality for fetching random dog images from the Dog API. The variable dog
is used to store the URL for the dog image (in the property message
of the response from the API). Whenever the dog
variable changes, the change is reflected in the img
element, which is used to display the image -- thus, the shown image is also changed.
In a similar way, we could use the Nameday API to fetch the namedays for a given day. Create a new component called Nameday.svelte
and place the following content to the file.
<script>
let nameday = $state("");
const day = $state(1);
const month = $state(1);
const fetchNameDay = async () => {
const data = {
day: day,
month: month,
country: "fi",
};
const response = await fetch("https://nameday.abalin.net/api/V1/getdate", {
headers: {
"Content-Type": "application/json",
},
method: "POST",
body: JSON.stringify(data),
});
const jsonData = await response.json();
nameday = jsonData.nameday.fi;
};
</script>
<button on:click={fetchNameDay}>Fetch nameday</button>
<p>Nameday: {nameday}</p>
With the above, we can fetch the nameday for 1st of January in Finland. The component could be expanded to take in the day and month as input from the user, and to allow the user to select the country.