Short intro to GraphQL

", "slug": "testimonial-2", "date": "2019/04/19", "type": "testimonial" } } ] } }}Instead of sending a request using REST to the WordPress REST API which in turn would have responded with more data than needed.

The GraphQL query received precisely the data that was asked for.

Something that’s really nice is selecting what data is need compared to a REST API.

In REST based APIs I usually send some requests with Postman and look at the responses to figure out what I need.

With GraphQL there are other tools, one that I used when using Gatsby was GraphiQL which lets you test out a query and see what you get back.

GraphiQL also has a good intellisense to helps find what keys are available to you.

When executing the query you get the response.

What I do is to play around in GraphiQL for awhile until I decided what I need.

Then I just copy the query I made and paste it in to the method graphql which is included in Gatsby.

With GraphQL there is only one endpoint you need to hit, that endpoint delivers the data based from your query.

To make more selective queries it’s possible to uses filters, it looks like this.

{ allWordpressWpTestimonial(filter: {slug:{eq: "testimonial-2"}}) { edges { node { id title excerpt slug date(formatString: "YYYY/MM/DD") } } }}This query gives back the Testimonial post type with the slug equal to “testimonial-2”.

The slug is nested within the node property, let’s say we had to query something nested one level deeper we could rewrite the filter like down below.

A side note: acf is short for Advance Custom fields it’s a plugin for WordPress to further enhance your data.

{ allWordpressWpTestimonial(filter: {acf:{grade: {eq: "2"}}}) { edges { node { id title excerpt slug date(formatString: "YYYY/MM/DD") acf { grade } } } }}If you would like to query for for then one post type it is possible to concatenate another query, just put it inside the outer braces.

{ allWordpressWpTestimonial { edges { node { id } } } allWordpressWpPortfolio { edges { node { id } } }}This query would be similar to making two http request to two different endpoints.

In SummaryGraphQL is a way to query for the data you need.

It solves the problem of under and over fetching data.

There are some very handy tools to play with the queries, I used GraphiQL which helped me find what keys I could use.

The data structure looks like a “keys only json”.

In REST you request a resource with GraphQL you request data based on a query.

A misconception is that GraphQL only works with React and JavaScript but there are implementation for other languages as well and the front end don’t have to be built with React.

.

. More details

Leave a Reply