How to use GraphQL in WordPress

GraphQL 06 Jun 2022 0
How to use GraphQL in WordPress

GraphQL is a relatively new query language for APIs.

As the documentations sais:

GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data. GraphQL provides a complete and understandable description of the data in your API, gives clients the power to ask for exactly what they need and nothing more, makes it easier to evolve APIs over time, and enables powerful developer tools.

Is possibile to use GraphQL in WordPress?

The answer is yes! Fortunately Jason Bahl has realized a free plugin called WPGraphQL which provides full portability to GraphQL and, as a plus, comes with an amazing graphical IDE for building queries at ease.

ACPT (from version 1.0.70) provides a full support to this fantastic plugin extending some of its features.

Install WPGraphQL and enable it for your CPTS

If don’t already tried it, do it. Install it from the offical WordPress repository.

Then you have to enable it for your CPTs: read the documentation on how to do this.

Once you’ve done open the GraphiQL IDE.

Run the first query

If are not familiar with GraphQL language maybe the GraphiQL IDE could be a good start to learn this language. Click on Query Composer button.

On the left, you have all the available queries. Suppose you have registered a custom post type called “movie”.

The IDE helps you to compose the query.

Start playing with some parameters, you’ll notice the query field is modifying.

The query object looks like a JSON file but it’s not. Look at this example:

{
  movies {
    edges {
      node {
          databaseId
        title
        acpt {
          meta {
            meta_box
            meta_fields {
              name
              type
              values
            }
          }
        }
      }
    }
  }
}

This query means:

  • find all movies
  • select only three nodes: the database ID, the title, and the acpt meta

You obtain something like that:

{
  "data": {
    "movies": {
      "edges": [
        {
          "node": {
            "databaseId": 2372,
            "title": "Il nome della rosa",
            "acpt": {
              "meta": [
                {
                  "meta_box": "info",
                  "meta_fields": [
                    {
                      "name": "altro",
                      "type": "Text",
                      "values": [
                        "dsadsadsadsa"
                      ]
                    },
                    {
                      "name": "url",
                      "type": "Url",
                      "values": [
                        "https://google.it"
                      ]
                    },
                    {
                      "name": "lista",
                      "type": "List",
                      "values": [
                        "fsdfds",
                        "fdsfsd",
                        "ff"
                      ]
                    }
                  ]
                }
              ]
            }
          }
        },
        {
          "node": {
            "databaseId": 2370,
            "title": "Another movie",
            "acpt": {
              "meta": [
                {
                  "meta_box": "info",
                  "meta_fields": [
                    {
                      "name": "altro",
                      "type": "Text",
                      "values": [
                        "hghghg"
                      ]
                    },
                    {
                      "name": "url",
                      "type": "Url",
                      "values": [
                        "https://google.it"
                      ]
                    },
                    {
                      "name": "lista",
                      "type": "List",
                      "values": [
                        "hghg",
                        "hhh"
                      ]
                    }
                  ]
                }
              ]
            }
          }
        },
        {
          "node": {
            "databaseId": 2265,
            "title": "Awsome movie",
            "acpt": {
              "meta": [
                {
                  "meta_box": "info",
                  "meta_fields": [
                    {
                      "name": "altro",
                      "type": "Text",
                      "values": [
                        ""
                      ]
                    },
                    {
                      "name": "url",
                      "type": "Url",
                      "values": [
                        ""
                      ]
                    },
                    {
                      "name": "lista",
                      "type": "List",
                      "values": []
                    }
                  ]
                }
              ]
            }
          }
        }
      ]
    }
  },
  "extensions": {
    "debug": [
      {
        "type": "DEBUG_LOGS_INACTIVE",
        "message": "GraphQL Debug logging is not active. To see debug logs, GRAPHQL_DEBUG must be enabled."
      }
    ]
  }
}

Run the query on a broswer

WPGraphQL exposes this endpoint:

http://your-website/index.php?graphql

First of all: every HTTP request to this endpoint must declare the Content-Type as application/json in the headers.

Second: the request must be a POST.

Third: every request MUST send the payload in this format:

{
    "query": "...",
    "variables" {}|null,
}

Where:

  • query is the pseudo JSON we now already know, in a plain text format (required field)
  • variables is a JSON object of variables for use in the query (optional field)

To replicate the query that we run in the GraphiQL run this curl:

curl --location --request POST 'http://your-website/index.php?graphql' \
--header 'Content-Type: application/json' \
--header 'Cookie: PHPSESSID=83eb3e8d90c4a5172ef0d3f283d6b040' \
--data-raw '{"query":"{\n  movies {\n    edges {\n      node {\n      \tdatabaseId\n        title\n        acpt {\n          meta {\n            meta_box\n            meta_fields {\n              name\n              type\n              values\n            }\n          }\n        }\n      }\n    }\n  }\n}","variables":null}'

Not exactly comfortable uh?

Run the query into your PHP code

Fortunately, WPGraphQL comes with a nice handy method called do_graphql_request to perform queries.

It’s super easy to use it.

$operation = 'basicMovieList';
$query = '
   query '.$operation.' {
      movies {
        edges {
          node {
            databaseId
            title
            acpt {
              meta {
                meta_box
                meta_fields {
                  name
                  type
                  values
                }
              }
            }
          }
        }
      }
    }
   ';

$variables = [];

$data = do_graphql_request( $query, $operation, $variables );

Now let’s break the do_graphql_request function:

  • $query (required): The GraphQL query string
  • $operation (optional): The name of the operation
  • $variables (optional): Array of variables to be passed to your GraphQL request

Sooo much better!

For more info please reference here:

Conclusion

GraphQL is an awesome tool to perform queries on your database in a fast, convenient and elengant way.

If you don’t have tried it, install WPGraphQL and start playing with it. You’ll fall in love with it, that’s a promise!

Comments

There are no comments yet

Please Post Your Comments & Reviews

20% Discount!


Use this code during check-out:

ACPT_2024_PROMO_20

Valid for all products*

*This coupon code is valid for all products and plans. The promotion expires December, 31st 2024 00:00:00 UTC

This will close in 20 seconds