DEV Community


Posted on • Updated on

Svelte: A Comprehensive Guide to Developing Your App With Svelte - Part 2

Hi welcome to part 2 of the comprehensive guide to Svelte.

In this article, we will be learning how to fetch API data using Svelte. We will be using the GitHub API to fetch data about repositories.

First, we need to install the Svelte npm package.

$ npm install svelte

Next, we need to create a file called app.svelte.


GitHub Repository Data

const url = "";

const request = new XMLHttpRequest();"GET", url, true);

request.onload = function() {
if (request.status === 200) {
const resp = request.response;

const data =;


request.onerror = function() {
console.error("request failed: " + request.status);


In the code, we first define the URL for the GitHub API. We then create a new XMLHttpRequest object. We open the GET request and set the URL. We also set the true parameter, which ensures that the request is made asynchronously.

We then define two functions, onload and onerror . onload will be executed when the request is loaded, while onerror will be executed if there is an error. We then send the request.

If the request is successful, we will get the response body. We will then extract the data from the body and log it to the console.

You can try running the code in your browser. You should see the data for all the repositories on GitHub.

Thanks for reading ☺️
Please follow me on git here

Discussion (2)

lukeshiru profile image
Luke Shiru

In 2022 you really don't need XMLHttpRequest, every supported browser out there already supports fetch, which has a way simpler API. Here's your code using fetch instead:

    .then(response => response.json())
Enter fullscreen mode Exit fullscreen mode

You might notice is way shorter ... and that's because it is πŸ˜… ... if using promises directly is confusing, you can always use top level await like this:

try {
    const response = await fetch("")
    const data = await response.json();
} catch (error) {
Enter fullscreen mode Exit fullscreen mode


yaku profile image
Yaku Author

Hey Lukeshiru, thanks for the correction I will update the article. I also think fetch is way neater πŸ˜…