How do I query an external GraphQL endpoint in Gatsby JS?
Asked Answered
L

3

7

I don't seen any clear way to query an outside GraphQL endpoint (i.e. https://somewebsite.com/graphql) for data. Has anyone else done this, and how did you do it?

I assume it requires you to build a custom plugin, but that seems overkill for such a simple need. I have searched the docs and this issue doesn't really ever get addressed. 🤔

Lugo answered 14/2, 2018 at 6:6 Comment(1)
I've looked at using apollo fetch, but that approach isn't very gatsby-ish, if you know what I mean.Lugo
R
4

In Gatsby V2 you don't need to create your own plugin.

What you need is a plugin called gatsby-source-graphql

gatsby-source-graphql uses schema stitching to combine the schema of a third-party API with the Gatsby schema.

You can find more info here.

Resht answered 11/12, 2018 at 16:31 Comment(0)
C
2

The answer is, as you mentioned, writing a new source plugin. This is how Gatsby gets the data into it's internal GraphQL structure to then query.

Plugins are, at their core, just additions to the gatsby-node, gatsby-browser, and gatsby-ssr files. So you could write the logic needed at the top of your gatsby-node file to avoid abstracting it out into it's own plugin.

Crampton answered 14/2, 2018 at 16:20 Comment(1)
This is the correct answer. You can also query external GraphQL endpoints as discussed with @sarasate. However, they will not be included in Gatsby's static data, and so won't be pre-fetched, removing most of the benefit of using Gatsby in the first place.Frye
B
0

If you're not so into writing plugins for gatsby, like me, have a look here. It explains in detail how you query any graphQL server via the Gatsby sourceNode API and the use of graphql-request.

Helped me to get data for e.g. from graph.cool as well as GraphCMS.

The problem though is that you always have to write 2 different kinds of graphQL queries, as they are usually not compatible to Gatsby's relay style queries. But still easier than building a whole plugin.

Borges answered 15/2, 2018 at 15:31 Comment(1)
Thanks Sarasate. I found this article too... and I came to the same conclusion. I will probably use this approach, though I still think it might be useful to learn the ins-and-outs of Gatsby plugin creation, just to have a more solid understanding. Thanks for chiming in.Lugo

© 2022 - 2024 — McMap. All rights reserved.