Raw GraphQL Querying

Avatar of Chris Coyier
Chris Coyier on

GraphQL has all kinds of awesome tooling built around it. But like everything on the web, it ultimately comes down to data shootin’ across the ol’ network and responses coming back. If you need to talk to a GraphQL API endpoint, you don’t absolutely have to use some kind of framework or library to make requests against it. As a matter of fact, you can do it pretty cleanly in vanilla JavaScript.

Take the Pokémon API, available in GraphQL, which I found via this list of APIs. It has a GraphiQL interface for exploring.

From that page, you can execute queries and see the results. You can also poke into the Network tab in DevTools and see the payload for requests it sends off, and see that it’s just a bit of JSON that is POSTed.

We can make our own JSON in that format too! First, we’ll make it an object in the right format, utilizing template literals to make the GraphQL query look nice (which is actually required because the query syntax is dependent on white-space). Then we JSON-ify it with the native JavaScript API and POST it via the also-native fetch API.

See the Pen
Raw GraphQL
by Chris Coyier (@chriscoyier)
on CodePen.

Easy cheesy. And no fancy tooling to request exactly what you need, which is the core benefit of GraphQL.