Contact Us:

670 Lafayette Ave, Brooklyn,
NY 11216

+1 800 966 4564
+1 800 9667 4558

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.
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.
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.
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.
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.
The body of an API call is the payload (or data) sent from the client to the server.
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:
Then, enter into the folder, install the required dependencies using npm and start a development server:
You should now see a “Hello, World!” message displayed in your browser at http://localhost:5000/.
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.
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:
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:
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:
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:
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:
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:
When pieced together, your App component should contain the following:
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.
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:
Change the markup in App.svelte to the following:
Then add the following line to the script block:
You should now see a list of post titles rendered to the page.
Consuming API in Svelte with Fetch 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:
To use Axios in our project, we first need to install it. In the project root, run:
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:
Also alter the code in the onMount hook like so:
And you should see the same results as previously in your browser.
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:
This is not unique to Axios. You’d apply the same method when working with the Fetch API.
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:
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
When compared with fetch(), Axios comes with some extra additions such as:
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.
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.
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.
© 2000 – 2022 SitePoint Pty. Ltd.
This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.


Leave a comment

Your email address will not be published. Required fields are marked *