Querying 'self' fields

Sometimes we need to modify the shape of the response, to emulate the same response from another GraphQL server, or from the REST API.

We can do this via the self field, added to all types in the GraphQL schema, which echoes back the same object where it is applied:

type QueryRoot {
self: QueryRoot!
}

type Post {
self: Post!
}

type User {
self: User!
}

How it works permalink

The self field allows to append extra levels to the query without leaving the queried object. Running this query:

{
__typename
self {
__typename
}

post(by: {id: 1}) {
self {
id
__typename
}
}

user(by: {id: 1}) {
self {
id
__typename
}
}
}

...produces this response:

{
"data": {
"__typename": "QueryRoot",
"self": {
"__typename": "QueryRoot"
},
"post": {
"self": {
"id": 1,
"__typename": "Post"
}
},
"user": {
"self": {
"id": 1,
"__typename": "User"
}
}
}
}

How to use permalink

Use self to artificially append the extra levels needed for the response, and field aliases to rename those levels appropriately.

For instance, this query recreates the shape of another GraphQL server:

{
categories: self {
edges: postCategories {
node: self {
name
slug
}
}
}
}

This query recreates the shape of the WP REST API:

{
post(by: {id: 1}) {
content: self {
rendered: content
}
}
}

Adding self fields to the endpoints permalink

Adding self fields to the schema can be configured as follows, in order of priority:

✅ Specific mode for the custom endpoint or persisted query, defined in the schema configuration

Adding self fields to the schema, set in the Schema configuration
Adding self fields to the schema, set in the Schema configuration

✅ Default mode, defined in the Settings

If the schema configuration has value "Default", it will use the mode defined in the Settings:

When to use permalink

The self field can be used to adapt the shape of the GraphQL response to some particular required shape, such as the one from another GraphQL server, or from the REST API.