WordPress and GraphQL

Pesquisar

Search for:

GraphQL is a emerging technology developed internally by Facebook and open-sourced right after. It is aimed to be a replacement of the REST API and more and more developers are buying the idea. GraphQL poses a declarative way of fetching and update data and thus simplifying the process of doing so on the front-end. Dealing with the server side of a GraphQL stack might be a bit more complex than building REST API endpoints, but the benefit is worth the challenge and fortunately there are several libraries out there that can help you build GraphQL servers.

If you’re a Javascript/Node developer you can leverage the Javascript Reference implementation which is a direct implementation of the GraphQL specification maintained by Facebook. If you’re more of a PHP developer you use the GraphQL-PHP library, even if you don’t work with any of these two languages, I’m sure there’s a library for you preferred language. If you never heard about GraphQL, I strongly recommend you to take the How To GraphQL tutorial, it will get you up to speed pretty quickly.

At 10up, we’re constantly building web sites with WordPress (that’s our expertise after all), but we’re leveraging modern technologies like React and Node more and more. Recently, I started digging into how GraphQL can help us build websites and I started to explore the WPGraphQL plugin, that essentially exposes a /graphql endpoint where you can execute queries using the GraphQL language.

I ended up building a small demo application that uses React and Apollo to consume data directly from WordPress. You can find the full code at my Github, needless to say, you’ll need a local WordPress instance running the WPGraphQL plugin. You might also need to update the GraphQL endpoint in src/index.js.

Below is a quick video showing the application running locally:

The REST API has already changed the way we build sites with WordPress, and GraphQL might be the evolution of that. It isn’t the solution for all problems and might not be any better than the REST API for some cases, but I’d definitely consider it on your next project.