Saif-Alislam Dekna
Saif-Alislam Dekna

Reputation: 107

Sveltekit - consume external REST api inside a component

Is it possible to consume external REST api in components? With the new breaking changes, I couldn't find an updated answer.

Appreciate any help.

Upvotes: 2

Views: 3771

Answers (2)

Yuriy Arhipov
Yuriy Arhipov

Reputation: 350

Good example from docs: https://kit.svelte.dev/docs/load#making-fetch-requests

/** @type {import('./$types').PageLoad} */
export async function load({ fetch, params }) {
  const res = await fetch(`/api/items/${params.id}`);
  const item = await res.json();
 
  return { item };
}

Upvotes: 0

gyurielf
gyurielf

Reputation: 413

Sure!

You can do a native fetch for any CRUD operations inside components.

Something similar like this:

let data;

const getData = async () => {
    const response = await fetch('https://your.endpoint/api/foo');
    if (response.headers.get('content-type')?.includes('application/json')) {
        const json = await response.json();
        return { response, json };
    } else {
        return { response };
    }
};

Then you can initialize whenever you want. E.g:

onMount(async ()=> {
    await getData();
})

Upvotes: 1

Related Questions