If you’re not yet familiar with GraphQL Queries, we recommend having a basic understanding before learning about Mutations.
Most discussions of GraphQL focus on data fetching, but any complete data platform needs a way to modify server-side data as well.
In REST, any request might end up causing some side-effects on the server, but by convention it’s suggested that one doesn’t use
GET requests to modify data. GraphQL is similar – technically any query could be implemented to cause a data write. However, it’s useful to establish a convention that any operations that cause writes should be sent explicitly via a mutation.
Just like in queries, if the mutation field returns an object type, you can ask for nested fields. This can be useful for fetching the new state of an object after an update. Let’s look at a simple example mutation, with the scenario being a form submission:
NOTE: The following mutations are not part of the core plugin, but have been added to this site for demonstration purposes. Out of the box, the core WPGraphQL mutations require the requests to be authenticated. Some demo mutations were registered for the sake of documentation without requiring authentication. Learn how to register mutations.
Note how the field
demoFormSubmission returns the
demoForm object with the submitted fields along with
dateSubmitted which returns a computed value based on the submission time. This is especially useful when mutating existing data, for example, when incrementing a field, since we can mutate data and query the new value of the fields in one request.
You might also notice that, in this example,
We can see that if we submit the form with a null value for either of the inputs, we will get an error in response, and GraphQL won’t even try to execute because it knows it’s an invalid request.
WPGraphQL Core Mutations
WPGraphQL comes bundled with a lot of mutations for core content types.
Any Post Type or Taxonomy that is registered properly
Below is a list of some of the mutations, but it’s recommended to explore the Schema with GraphiQL or any other tool for browsing a GraphQL Schema to get familiar with what mutations exist for your particular WordPress site, based on what Post Types, Taxonomies, Settings, etc have been registered.
Authentication and Authorization
WPGraphQL tries to enforce authentication and authorization during mutations. For example, WordPress core requires users to have the capability
create_post in order to create posts. WPGraphQL respects
Let’s try and mutate some data without being authenticated:
As an unauthenticated user to this site, this mutation won’t fulfill the mutation, no page will be created, and an error will be returned.
If you copy and paste this into your WPGraphiQL in your WordPress dashboard and execute, a page will be created, as you would be an authenticated user on that site.