How to Fetch Data in Svelte

Share this article

How to Fetch Data in Svelte

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.

Note: you can dig deeper into this topic in “What Is a REST API?”.

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

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 <script> block for our JavaScript, a <style> block for our styles, as well as a <main> tag with our markup. This is the basic anatomy of a Svelte component.

Let’s start by importing the onMount hook from Svelte, like so:

import { onMount } from "svelte";

The onMount hook in Svelte is a lifecycle method used to define instructions that should be carried out once the component where it’s used is first rendered in the DOM tree.

If you’re coming from a React background, you should notice that onMount hook in Svelte works similarly to the componentDidMount() method in class-based React components or the useEffect() hook in React functional components.

Next, we’re going to define a variable to hold the URL of the endpoint we intend to use:

const endpoint = "https://jsonplaceholder.typicode.com/posts";

Note: JSONPlaceholder is a handy, free, online REST API that you can use whenever you need some fake data.

Next, create a posts variable and assign an empty array to it:

let posts = [];

This empty posts array is going to be filled up with the data we receive from our API once we make the call.

Finally, we can now make use of the onMount() method to make a GET request to the endpoint using JavaScript’s Fetch API as shown below:

onMount(async function () {
  const response = await fetch(endpoint);
  const data = await response.json();
  console.log(data);
});

When pieced together, your App component should contain the following:

<script>
  import { onMount } from "svelte";
  const endpoint = "https://jsonplaceholder.typicode.com/posts";
  let posts = [];

  onMount(async function () {
    const response = await fetch(endpoint);
    const data = await response.json();
    console.log(data);
  });

  export let name;
</script>

<main>
  <h1>Hello {name}!</h1>
  <p>Visit the <a href="https://svelte.dev/tutorial">Svelte tutorial</a> to learn how to build Svelte apps.</p>
</main>

<style>
  /* ommitted for brevity */
</style>

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}
  <div>
    <p>{article.title}</p>
  </div>
{/each}

Change the markup in App.svelte to the following:

<main>
  <h1>Hello {name}!</h1>
  <p>Visit the <a href="https://svelte.dev/tutorial">Svelte tutorial</a> to learn how to build Svelte apps.</p>

  {#each posts as article}
    <div>
      <p>{article.title}</p>
    </div>
  {/each}
</main>

Then add the following line to the script block:

posts = data;

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

Consuming API in Svelte with Fetch API

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 axios@0.21.1

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) => {
  //this will be executed only when all requests are complete
  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.

consuming api in svelte with AXIOS

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.

FAQs about Fetching Data with Svelte

How do I fetch data in a Svelte component?

Svelte provides a built-in fetch() function that you can use to make HTTP requests. You can use it directly in the <script> block of your Svelte component to fetch data from a server.

Can I use async/await with the fetch function in Svelte?

A: Yes, you can use async/await syntax with the fetch function in Svelte. Simply define an async function in the <script> block and use the await keyword with the fetch function.

What is the recommended way to handle loading and error states during data fetching?

Svelte provides a convenient way to handle loading and error states by using the {#await} and {#catch} blocks. You can wrap your fetch call with these blocks to handle the loading state and potential errors.

Can I use third-party libraries for data fetching in Svelte?

Yes, you can use third-party libraries like axios or fetch-mock for data fetching in Svelte. Simply import the library into your component and use it as you would in a regular JavaScript environment.

Is it possible to fetch data during server-side rendering (SSR) in Svelte?

Yes, SvelteKit, the framework built on top of Svelte, supports server-side rendering. You can use the $fetch function in the load function of your routes to fetch data on the server before rendering the page.

David AdeneyeDavid Adeneye
View Author

I'm an engineer with a passion for how system software works. I'm skilled in front-end development, web design, IT, and software development. I have a Bachelor's degree in Computer Science from Olabisi Onabanjo University, and experience as both a technical writer and lecturer.

rest apisvelte
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week