GraphQL queries, mutations and subscriptions

Three different operation types can be used to send requests to a GraphQL server: queries, mutations and subscriptions. Let’s look at them one by one.

Queries

The query operation is used when we want to retrieve data from the GraphQL server. You could compare it to an HTTP GET request in RESTful APIs. In the example below, we are asking for information on a user (the one with an id of 1) and we are specifying we want their id, username and email:

And here’s a typical response a GraphQL server would return:

Mutations

The mutation operation is used when we want to create or modify data on the GraphQL server. You could compare it to an HTTP POST, PUT, or DELETE request in RESTful APIs. Here’s an example of a GraphQL mutation operation:

Here, we are creating a new user in the system, specifying their username and email. we are also asking the GraphQL server to send back the id it applied to the new user, along with the username and email values we specified, for confirmation.

Here’s the response:

Subscriptions

The subscription operation is used for setting up real-time updates. It allows a client application to receive updates whenever specific events occur on the server.

To enable real-time updates, the client and server will usually perform a handshake to upgrade the HTTP connection to a Websocket connexion.

Here’s an example of a GraphQL subscription operation:

In the present case, we want to listen for new messages in a specific chat channel whose channelId is 123. When a new message is sent to that channel, the server will push the message data to us in real-time.

Here’s a typical message the server would push back:

Now that you’re familiar with the three different operation types you can use in GraphQL, you’re ready to start writing your own GraphQL requests, which will conveniently be the topic of my next post. So stick around. šŸ˜‰

Hi! I'm a tech journalist, getting my feet wet in ethical hacking. What you will find here is me taking notes on the tools and techniques Iā€™m learning and offering answers to the questions I had when I first got started not so very long ago.

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top