Skip to main content

Working with Svelte

If you love Svelte's simplicity, you'll love how easy and fast it is to integrate your API into your Svelte projects.

Let's take a look at that process now.

Starting up a Svelte project

If you're interested in jumping straight in, Svelte has documentation on the easiest way to start a Svelte app.

For simplicity's sake, we'll be using Svelte's Hello World example project. Download it and open up your terminal inside the project directory to begin. You'll need to install all the project's dependencies. Run:

npm install

And you're ready to go.

Setup

To connect to your project, you need your API Endpoint and an API key.

If you haven't created a project yet, follow this guide to do so.

If you already have a project, your API Endpoint will be in the admin UI. In the home tab, look for the "Useful Snippets" section.

Copy the API Endpoint and save it somewhere secure.

To get an API Key, you'll have to create one. Read our docs on creating an API Key here.

danger

API keys used in frontend applications are exposed to the browser, even if you use environment variables. When you create an API Key, always use the fewest permissions necessary for your application. Learn more in our permissions guide.

INFO

Environment variables have no officially-supported implementation in Svelte yet, so be sure to give your API Key read-only permissions when you create it.

Connecting Svelte to the API

Creating an Apollo client

Apollo is the simplest way to add GraphQL queries to your Svelte components. To get an Apollo client running, let's first install all the necessary dependencies:

npm i @apollo/client svelte-apollo apollo-cache-inmemory apollo-link-http graphql-tag

With that done, open up the App.svelte file in the src folder of your project. It's time to configure our Apollo client.

In the <script> tags of your component, import all the necessary dependencies as shown below:

App.svelte
<script>
import { ApolloClient } from "@apollo/client";
import { setClient } from "svelte-apollo";
import { query } from "svelte-apollo";
import { InMemoryCache } from "apollo-cache-inmemory";
import { HttpLink } from "apollo-link-http";
import gql from 'graphql-tag'
</script>

Now we're ready for our Apollo client configuration code. Start with creating an HttpLink object, which will take our Endpoint and API Key, so we can connect to your project.

App.svelte
	const link = new HttpLink({
uri: 'https://api.takeshape.io/project/6cdbcc52-5697-475b-872e-fcb6fd0e00d0/graphql',
fetch,
headers: {
Authorization : `Bearer 7b9171f34e104aeba972941bcfb7767d`
}
});

Almost done. Now we'll create an ApolloClient object, which will manage our connection to your project's endpoint. All that's necessary after that is setting the client with the setClient method we imported.

App.svelte
	const client = new ApolloClient({
link: link,
cache: new InMemoryCache({
addTypename: true
})
});
setClient(client);

We're all set. Now to make a query, we just define it using the gql tag we've imported. For this example, we'll be pulling data about product collections from an Ecommerce backend. Here's an example query:

App.svelte
	const collectionList = query(gql`
query {
getCollectionList{
items{
_id
title
products{
name
price
}
}
}
}
`)

Your entire <script> should look like this:

App.svelte
<script>
import { ApolloClient } from "@apollo/client";
import { setClient } from "svelte-apollo";
import { query } from "svelte-apollo";
import { InMemoryCache } from "apollo-cache-inmemory";
import { HttpLink } from "apollo-link-http";
import gql from 'graphql-tag'

const link = new HttpLink({
uri: 'https://api.takeshape.io/project/6cdbcc52-5697-475b-872e-fcb6fd0e00d0/graphql',
fetch,
headers: {
Authorization : `Bearer 7b9171f34e104aeba972941bcfb7767d`
}
});

const client = new ApolloClient({
link: link,
cache: new InMemoryCache({
addTypename: true
})
});
setClient(client);

const collectionList = query(gql`
query {
getCollectionList{
items{
_id
title
products{
name
price
}
}
}
}
`)
</script>

Adding data to your Svelte template

Here's the part that makes Svelte so beautiful. Adding data to your template is super easy. You'll use an #if block to conditionally render content based on whether the data has been loaded.

Within the #if block, we'll use #each blocks to render out HTML based on each piece of data we receive in the response from your project's API. Check the code below:

App.svelte
{#if $collectionList.loading}
Loading...
{:else if $collectionList.error}
Error: {$collectionList.error.message}
{:else}
{#each $collectionList.data.getCollectionList.items as collection}
<h2>{collection.title}</h2>
<ul>
{#each collection.products as product}
<li>{product.name} : {product.price}</li>
{/each}
</ul>
{/each}
{/if}

In the above code, we're waiting for our query to resolve and return data to our collectionList variable. Once that's done, we're cycling through its items array and rendering an <h2> and <ul> for each item. In this case, items represents our product collections. The list will be every product in the collection we're iterating over, alongside its price.

The final page should look like this:

And the full App.svelte component should look like this:

App.svelte
<script>
import { ApolloClient } from "@apollo/client";
import { setClient } from "svelte-apollo";
import { query } from "svelte-apollo";
import { InMemoryCache } from "apollo-cache-inmemory";
import { HttpLink } from "apollo-link-http";
import gql from 'graphql-tag'

const link = new HttpLink({
uri: 'https://api.takeshape.io/project/6cdbcc52-5697-475b-872e-fcb6fd0e00d0/graphql',
fetch,
headers: {
Authorization : `Bearer 7b9171f34e104aeba972941bcfb7767d`
}
});

const client = new ApolloClient({
link: link,
cache: new InMemoryCache({
addTypename: true
})
});
setClient(client);

const collectionList = query(gql`
query {
getCollectionList{
items{
_id
title
products{
name
price
}
}
}
}
`)
</script>

{#if $collectionList.loading}
Loading...
{:else if $collectionList.error}
Error: {$collectionList.error.message}
{:else}
{#each $collectionList.data.getCollectionList.items as collection}
<h2>{collection.title}</h2>
<ul>
{#each collection.products as product}
<li>{product.name} : {product.price}</li>
{/each}
</ul>
{/each}
{/if}

And you're ready to get rolling with Svelte.

Still need help? Get in touch with us.