In this post we'll look at how you can perform SvelteKit GraphQL queries using fetch only. That's right, there's no need to add Apollo client or urql to your Svelte apps if you have basic GraphQL requirements. We will get our GraphQL data from the remote API using just fetch functionality. You probably already know that the fetch API is available in client code . In SvelteKit it is also available in load functions and server API routes. This means you can use the code we produce here to make GraphQL queries directly from page components or any server route.
We will use a currency API to pull the latest exchange rates for a few currencies, querying initially from a server API route. This will be super useful for a backend dashboard on your platform. You can use it to track payments received in foreign currencies, converting them back to your local currency be that dollars, rupees, euros, pounds or even none of those! This will be so handy if you are selling courses, merch or even web development services globally. Once the basics are up and running we will add an additional query from a client page and see how easy Svelte stores make it to update your user interface with fresh data.
If that all sounds exciting to you, then let's not waste any time!
We'll start by creating a new project and installing packages:
When prompted choose a Skeleton Project and answer Yes to TypeScript, ESLint and Prettier.
We will be using the SWOP GraphQL API to pull the latest available currency exchange rates. To use the service we will need an API key. There is a free developer tier and you only need an email address to sign up. Let's go to the sign up page now, sign up , confirm our email address and then make a note of our new API key.
dotenv now so we can start using the API quick sticks.
dotenv package and the following font which we will use
svelte.config.js to use
Finally, create a
.env file in the project root folder containing your
With the preliminaries out of the way let's write our query.
To create a GraphQL query using fetch, basically all you need to do is create a query object and a
variables object, convert them to a string and then send them as the body to the right API
endpoint. We will use
fetch to do the sending as it is already included
in SvelteKit though you could choose
axios or some other package if
you wanted to. In addition to the body, we need to make sure we include the right auth headers (as
you would with Apollo client or urql).
That's enough theory. If you want to do some more reading, Jason Lengstorf from Netlify wrote a fantastic article with plenty of extra details.
Let's write some code. Create a file at
src/routes/query/fx-rates.json.ts and paste in the following code:
This is code for a fetch API route making use of SvelteKit's router. To invoke this code from a
client, we just send a
POST request to
/query/fx-rates.json with that path being derived from the file's path. We will do this together shortly, so just carry
on if this is not yet crystal clear.
You can see in lines
define the GraphQL query. This uses regular GraphQL syntax. Just below we define our query variables.
If you are making a different query which does not need any variables, be sure to include an empty
31 you see we make a fetch request to the SWOP API. Importantly,
we include the
Content-Type header, set to
application/json in line
34. The rest of the file just processes the response
and relays it back to the client.
Let's create a store to save retrieved data next.
We will create a store as our “single source of truth”. Stores are an idiomatic Svelte way of sharing app state between components. We won't go into much detail here and you can learn more about Svelte stores in the Svelte tutorial .
To build the store, all we need to do is create the following file. Let's do that now, pasting the
content below into
src/lib/shared/stores/rates.ts (you will need to
create new folders):
Next, we can go client side to make use of SvelteKit GraphQL queries using fetch only.
We are using TypeScript in this project, but very little, so hopefully you can follow along even
though you are not completely familiar with TypeScript. Replace the content of
src/routes/index.svelte with the following:
With TypeScript you can define variable types alongside the variable. So in line
25, we are saying that data is an object with a single field;
latest itself is an array of objects (representing currency pairs
in our case). Each of these objects has the following fields:
quote. You see the type of each of these declared alongside it.
<script> block contains a load function. In SvelteKit,
load functions contain code which runs before the initial render. It makes sense to call the API route
we just created from here. We do that using the fetch call in lines
11. Notice how the url matches the file path for the file
we created. The JSON response is sent as a prop (from the return statement in lines
Another interesting line comes in the second
Here at line
23, we import the store we just created. Line
24 is where we import the props we mentioned as a
data prop. The types
come from the object we expect the API to return. It is not too much hassle to type this out for a
basic application like this one. For a more sophisticated app, you might want to generate types automatically.
In a follow-up post, we see how you can generate the types automatically with
Next we actually make use of the store. We add the query result to the store in line
27. We will actually render whatever is in the store rather than the result of the query directly.
The benefit of doing it that way is that we can easily update what is rendered by adding another
other currency pair to the store (without any complex logic for merging what is already rendered
with new query results). You will see this shortly.
This should all work as is. Optionally add a little style before continuing:
src/routes/index.svelte — click to expand code.
Ok let's take a peek at what we have so far by going to localhost:3000/ .
Finally we will look at how updating the store updates the user interface We will add a form in
which the user can add a new currency. Edit
82 you see using Svelte it is pretty easy to link the value
newCurrency variable here. In our
handleSubmit function, we call our API route
once more, this time only requesting the additional currency. In line
45 we see updating state is a piece of cake using stores. We just spread the current value of the rate
store (this is nothing more than an array of the existing five currency objects) and tack the new one
on the end.
Try this out yourself, adding a couple of currencies. The interface should update straight away.
In this post we learned:
- how to do SvelteKit GraphQL queries using fetch instead of Apollo client or urql,
- a way to get up-to-date currency exchange rate information into your site backend dashboard for analysis, accounting and so many other uses,
- how stores can be used in Svelte to update state.
See the follow-up post in which we automatically generate TypeScript types for the GraphQL API . Type generation is not too onerous in this example, though you can see how to do ti automatically for more intricate GraphQL APIs, getting free autocompletion and help spotting code errors.
There are some restrictions on the base currency in SWOP's developer mode. The maths (math) to convert from EUR to the desired base currency isn't too complicated though. You could implement a utility function to do the conversion in the API route file. If you do find the service useful, or and expect to use it a lot, consider supporting the project by upgrading your account.
As an extension you might consider pulling historical data from the SWOP API, this is not too different, to the GraphQL query above. Have play in the SWOP GraphQL Playground to discover more of the endless possibilities . Finally you might also find the Purchasing Power API handy if you are looking at currencies. This is not a GraphQL API though it might be quite helpful for pricing your courses in global economies you are not familiar with.
Is there something from this post you can leverage for a side project or even client project? I hope so! Let me know if there is anything in the post that I can improve on, for any one else creating this project. You can leave a comment below, @ me on Twitter or try one of the other contact methods listed below.
- SvelteKit makes fetch available in load functions and on endpoints. This is a great alternative to Apollo Client and URQL when you want to get up and running quickly on your new project. Although you won't have access to the caching features provided by Apollo Client and URQL if you use just fetch, SvelteKit does make it easy to create a cache using stores. The advantages of using fetch are you keep you app lighter, with fewer dependencies and also that the API is very stable. This saves you refactoring code as APIs change.
- Using fetch for GraphQL queries is as simple as creating a query and variables object and sending those to your endpoint. In the case your query does not need any variables, you will still need to include an albeit empty variable object in the request. The query variable is the GraphQL query (or mutation) using regular GraphQL syntax, as a string. We use the POST method to send the query to our external API. Importantly, we include the 'Content-Type': 'application/json' HTTP header in the request.
- In this tutorial we run through an example using an FX rate GraphQL API to fetch data. We make GraphQL calls both from the client code and out API endpoints. There is also a link to the complete tutorial project code on GitHub at the bottom of the article. You can follow along, building the project out yourself, or just jump straight to the GitHub repo.
Have you found the post useful? Do you have your own methods for solving this problem? Let me know your solution. Would you like to see posts on another topic instead? Get in touch with ideas for new posts. Also if you like my writing style, get in touch if I can write some posts for your company site on a consultancy basis. Read on to find ways to get in touch, further below. If you want to support posts similar to this one and can spare a few dollars, euros or pounds, please consider supporting me through Buy me a Coffee .
Finally, feel free to share the post on your social media accounts for all your followers who will find it useful. As well as leaving a comment below, you can get in touch via @askRodney on Twitter and also askRodney on Telegram . Also, see further ways to get in touch with Rodney Lab . I post regularly on SvelteKit as well as other topics. Also subscribe to the newsletter to keep up-to-date with our latest projects.