DEV Community

Khutso siema
Khutso siema

Posted on


In this article i will share with you two techniques of consuming a rest api in svelte.

So basically, "consume an API" is just a fancy term for "use an API".
Disappointed? Don't be,You might learn something.

Method #1

The most common way to fetch data from other sources in svelte is to use the onMount lifecycle function.

here's an example from my last post

 import { onMount } from "svelte";

let myTodo;
     const response = await fetch("")
      const todo = await response.json();
      myTodo = todo

  {#if myTodo}
Enter fullscreen mode Exit fullscreen mode

Let's say for some reason you don't want to fetch the data by using onMount lifecycle function,let's say for some reason you want to await the value of promises directly in your markup,well your in luck because svelte can do just that.
which brings me to

Method #2

 let myTodo = getTodo();

 async function getTodo() {
   const response = await fetch("");
   const todo = await response.json();

   if (response.ok) {
     return todo;
   } else {
     throw new Error(todo);


{#await myTodo}
{:then todo_1}
{:catch error}
    <p style="color: red">{error.message}</p>

Enter fullscreen mode Exit fullscreen mode

Hope this was helpful to someone out there!

Thanks for reading and stay tuned!

Top comments (4)

mayconbalves profile image
Maycon Alves

Greate article =)

fultonbrowne profile image
Fulton Browne

Great article, there needs to me more tutorials about REST, thanks for adding one :]

manyeya profile image
Khutso siema

Thank you for reading,will try my best to write more about REST

pmutua profile image
Philip Mutua • Edited

Thank you for the tutorial. How do you handle endpoints that require authentication e.g jwt ?