DEV Community

Khutso siema
Khutso siema

Posted on

HOW TO CONSUME A RESTFUL API IN SVELTE

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


<script>
 import { onMount } from "svelte";

let myTodo;
  onMount(async()=>{
     const response = await fetch("https://jsonplaceholder.typicode.com/todos/1")
      const todo = await response.json();
      myTodo = todo
  });
</script>

<div>
  {#if myTodo}
    <ul>
      <li>{myTodo.title}</li>
    </ul>
  {:else}
    <p>loading.....</p>
  {/if}
</div>
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

<script>
 let myTodo = getTodo();

 async function getTodo() {
   const response = await fetch("https://jsonplaceholder.typicode.com/todos/1");
   const todo = await response.json();

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

</script>

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

Enter fullscreen mode Exit fullscreen mode

Hope this was helpful to someone out there!


Thanks for reading and stay tuned!

Top comments (4)

Collapse
 
mayconbalves profile image
Maycon Alves

Greate article =)

Collapse
 
fultonbrowne profile image
Fulton Browne

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

Collapse
 
manyeya profile image
Khutso siema

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

Collapse
 
pmutua profile image
Philip Mutua • Edited

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