Using APIs
Learning objectives
- You know the basics of using APIs with Svelte.
As we are programming with JavaScript, we can use the JavaScript Fetch API for retrieving content from APIs. Let's start with using the API end point at https://simple-joke-api.deno.dev/random
that we have also used in the Web Software Development course. The API responds to GET requests with JSON data that has a setup and a punchline -- a sample response could be as follows.
{
setup: "What's the object-oriented way to become wealthy?",
punchline: "Inheritance"
}
The following component outlines the basic concepts of making a request using the Fetch API, retrieving JSON content from the request, and showing the response to the user.
<script>
let joke = {};
const fetchJoke = () => {
fetch('https://simple-joke-api.deno.dev/random')
.then((response) => response.json())
.then((jsonData) => {
joke = jsonData;
});
};
</script>
<button on:click={fetchJoke}>Fetch a joke</button>
{#if joke.setup}
<p>Setup: {joke.setup}</p>
<p>Punchline: {joke.punchline}</p>
{/if}
The fetch method is an asynchronous method. In the above example, the asynchronous functionality is handled using the then
method in the Promise that is returned when fetch
is called. The json method of the Response is similarly asynchronous, so that is also handled with the then
method. Finally, when the response has been received and transformed to a JSON object, the value for the variable joke
is set, and the joke is shown to the user.
Svelte's HTML template has also an await
block for handling promises in the markup. We could also implement the above functionality as an asynchronous method, which could be called when the component is loaded. With the await
block, we could also show the user an indication that the content is loading (e.g. a spinner).
<script>
const fetchJoke = async () => {
const response = await fetch('https://simple-joke-api.deno.dev/random');
return await response.json();
};
let jokePromise = fetchJoke();
const updateJoke = () => {
jokePromise = fetchJoke();
};
</script>
<button on:click={updateJoke}>Fetch a joke</button>
{#await jokePromise}
<p>Loading...</p>
{:then joke}
<p>Setup: {joke.setup}</p>
<p>Punchline: {joke.punchline}</p>
{/await}
Posting and so on..
The Fetch API has support for all the basic HTTP requests, including posting data. For additional information, check out its documentation at https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch.
Note that when working with APIs through the browser, we are limited to APIs that support Cross-origin Resource Sharing.
Integrating Svelte with our Docker Compose project?
We'll look into integrating Svelte with our Docker Compose project once we've learned a bit about Astro in the next chapter.