How to Fetch Data in Svelte – SitePoint

This tutorial explores how you can consume and render data from an API in your Svelte application. You can interact with APIs in Svelte in the onMount() lifecycle hook using either Axios, Apisauce, JavaScript’s native Fetch API, or any HTTP client of your choice.
We’ll build a sample application that interacts and displays data provided by a REST API server. This application will allow users to fetch lists of blog posts from a REST API and display them on the page.
Prerequisites
In order to follow this tutorial, you’ll need to have some prior knowledge of JavaScript and CSS, as well as some familiarity with Svelte.
You’ll also need Node and npm installed on your machine, as well as Git.
What Is a REST API?
The acronym API stands for “application programming interface”, and in simple terms, it’s a way for two applications to communicate — or share data with each other.
A REST API is a type of API that implements the representational state transfer (REST) protocol. REST is an architectural style for building web services that interact via an HTTP protocol. The request structure of REST includes four essential parts, which are the HTTP method, an endpoint, headers, and the request body.
HTTP Methods
The HTTP method in an API request tells the server what kind of action the client expects it to perform. The most widely used HTTP methods today include GET, POST, PATCH, DELETE and are explained briefly below.
GET: used to fetch or read information from a server
POST: used to create or store records in a server
PUT / PATCH: used to update or patch records in a server
DELETE: used to delete one or more records from a resource point
HTTP Endpoints
An HTTP endpoint in basic terms is an address or URL that specifies where one or more resources can be accessed by an API.

HTTP headers are key-value pairs that let the client pass information to the server in a request and vice-versa in a response.
Request Body
The body of an API call is the payload (or data) sent from the client to the server.
Setting Up our Svelte App
We’ll build a sample application that interacts with an external REST API to fetch a list of blog posts from a server. We’ll then display this list on the Svelte client.
We’re not going to dive too much into bundling and the infrastructure of Svelte apps in this tutorial, so we’ll follow the instructions on the official Svelte site to get an application up and running.
In your preferred directory, run:
npx degit sveltejs/template svelte-demo-app

Then, enter into the folder, install the required dependencies using npm and start a development server:
cd svelte-demo-app
npm install
npm run dev –open

You should now see a “Hello, World!” message displayed in your browser at http://localhost:5000/.
Using the Fetch API to Consume a REST API
In this article, we’ll examine two methods of fetching data from an API. Firstly, we’ll look at using the Fetch API, which is native to JavaScript. Then in the next section we’ll look at using the Axios client, before briefly comparing and contrasting the two methods after that.
What is the Fetch API?
The Fetch API is a promise-based mechanism that allows you to make asynchronous API requests to endpoints in JavaScript. If you’re familiar with the XMLHttpRequest() method, you’ll probably agree that the Fetch API is an improvement — in the sense that it provides additional features such as data caching, the ability to read streaming responses, and more.
Using the Fetch API is as easy as calling the fetch() method with the path to the resource you’re fetching as a required parameter. For example:
const response = fetch(‘your-api-url.com/endpoint’);

Passing more parameters in a request
The fetch() method also allows you to be more specific with the request you’re making by passing an init object as an optional second parameter.
The init object allows you pass extra details along with your request. The most common of these are listed below:
method: a string that specifies what HTTP method is being sent to the server and can be one of GET, POST, PUT, PATCH or DELETE.
cache: a string that specifies if the request should be cached. Allowed options are default, no-cache, reload, force-cache, only-if-cached.
headers: an object used to set headers to be passed along with the request example.
body: an object most commonly used in POST, PUT or PATCH requests. It allows you pass a payload to the server.
Building out the App component
Once your Svelte scaffolding has been completed, open up the src folder and locate the App.svelte component. This is what is rendered when you visit the project’s home page.
As you can see, the component contains a

Hello {name}!

Visit the Svelte tutorial to learn how to build Svelte apps.

To check this is working, save the file, then visit http://localhost:3000/ and check the browser’s dev tools. You should see an array of objects logged to the console.
Note: if you’re wondering about that export let name; statement, this is how we define props in Svelte. The export keyword here declares that this value is a prop that will be provided by the component’s parent.
Displaying data from the endpoint
Now that we’ve been able to successfully pull data from our endpoint, it’s time to render the content on our page. We can do this using an each block:
{#each posts as article}

{article.title}

{/each}

Change the markup in App.svelte to the following:

Hello {name}!

Visit the Svelte tutorial to learn how to build Svelte apps.

{#each posts as article}

{article.title}

{/each}

Then add the following line to the script block:
posts = data;

You should now see a list of post titles rendered to the page.

Using the Axios Client to Consume a REST API
Axios is an open-source, promise-based JavaScript library for making API calls that’s quite similar to the Fetch API. Axios provides some specific methods for performing various API requests. For example:
axios.get() is used to make a GET http request to an endpoint
axios.post() is used to make a POST request when creating records
either of axios.patch() and axios.put() can be used when you need to make an HTTP request to update a record in the API
axios.delete() is used to send an HTTP DELETE request to an endpoint
Installing Axios and updating the App component
To use Axios in our project, we first need to install it. In the project root, run:
npm i [email protected]

Note: I’m installing a slightly older version here, as a recent version of the library introduced a bug, which results in a TypeError: Cannot convert undefined or null to object error when using Axios in a Svelte component. See here and here. Hopefully this will be fixed by a future version of the library.
Then, in the App component, include the library:
import axios from "axios";

Also alter the code in the onMount hook like so:
onMount(async function () {
const response = await axios.get(endpoint);
console.log(response.data);
posts = response.data;
});

And you should see the same results as previously in your browser.
Error handling
As the Ajax request is being made inside an async function, we’d need to use a try … catch block to report on anything going wrong:
onMount(async function () {
try {
const response = await axios.get(endpoint);
console.log(response.data);
posts = response.data;
} catch (error) {
console.error(error);
}
});

This is not unique to Axios. You’d apply the same method when working with the Fetch API.
Grouped requests in Axios
One nice feature of Axios is that you can make simultaneous HTTP requests to multiple endpoints using the axios.all() method. This method takes in a group of requests as an array and returns a single promise object that only resolves when the requests of the array passed in have been individually resolved.
The syntax for doing this is shown in the snippet below:
axios.all([
axios.get("https://jsonplaceholder.typicode.com/posts"),
axios.get("https://jsonplaceholder.typicode.com/comments"),
])
.then((responseArr) => {

console.log("First Post: ", responseArr[0].data[0].title);
console.log("Second Comment: ", responseArr[1].data[1].body);
})
.catch((error) => {
console.log(error);
});

Here (for the sake of variation) I’m chaining the methods using then() and using catch() to deal with errors.

Axios vs Fetch
When compared with fetch(), Axios comes with some extra additions such as:
request and response interception
a better streamlined error handling process
XSRF protection
upload progress support
response timeout
the ability to cancel requests
support for older browsers
automatic JSON data transformation
Also, Axios can be used in both the browser and with Node.js. This facilitates sharing JavaScript code between the browser and the back end or doing server-side rendering of your front-end apps.
You can read about some further differences here.
Conclusion
We’ve covered a lot in this walkthrough. We started by taking a look at what a REST API is and why you might want to consume an external service in your app. Then we set up a Svelte project and used the Fetch API to pull a list of articles from a dummy API using the Svelte onMount method. Finally, we took a look at the Axios HTTP library and then rewrote our script to consume our mock API using Axios instead of the Fetch API.
I hope you enjoyed reading through this guide, and hopefully it’s introduced you to some techniques for consuming a REST API in a Svelte application. We took a pragmatic approach to explore how to work with REST APIs using the onMount lifecycle method with the Fetch API and the Axios client.
This article will serve as a reference guide any time you need to work with a REST API in a Svelte application.

Coded at

Share your love

Leave a Reply