How GraphQL Works Under the Hood
HTTP Requests with GraphQL
Tools like GraphiQL essentially construct HTTP requests to communicate with the GraphQL server. We just wrote a basic query to retrieve the base URLs of our store. What you might not have realized is that when we submitted this query it executed a simple HTTP POST request, although it may seem that something more complicated is going on in the background.
To get a clearer picture of the actual request, we can use a browser plugin called GraphQL Network Inspector. After installing this plugin, refresh your page and open the Chrome Developer Tools. You will now see a new "GraphQL Network" tab. Execute your earlier query again, and you will see the request appear in the list of network calls.
Click on the specific request, and you will be directed to the "Request" tab with details about the request. The "Headers" tab displays all the information that was transmitted during the request, including the HTTP method, cookie data, user agent, and response headers. The "Response" tab shows the response's prettified version which includes collapsible sections, as well as the raw response from the request.
POST Request vs GET Request
You may be wondering why GraphQL used a POST request for data retrieval rather than the usual GET request that occurs when calling other APIs over HTTP. The main reason is that GET requests cannot have a request body, which means queries and variables must instead be sent as query parameters. This can result in issues when dealing with larger queries, and some servers may return a 414 URI Too Long
error if the request is too large.
To avoid issues such as these, it is best practice to use POST requests with the application/json
content type when working with GraphQL. By doing so, you won't encounter limitations when creating queries or need to find alternative methods for sending data to the GraphQL server.
GraphQL and Transport Mechanisms
An essential aspect of GraphQL is that it is transport-agnostic, meaning it doesn't rely solely on HTTP. While HTTP is the most common transport mechanism for Magento 2, GraphQL can work with other transport services, giving you more flexibility according to your requirements.
Some alternative transport mechanisms for GraphQL include:
- WebSockets
- Server-Sent Events (SSE)
- gRPC
- Message Queues
- Custom Protocols
However, it's worth noting that using non-HTTP transport mechanisms for GraphQL might require additional tooling, libraries, or custom implementations.
Explicit Data Retrieval with GraphQL
One significant advantage of GraphQL queries compared to REST is its ability to explicitly define the exact fields to be returned. This capability allows you to save bandwidth by preventing unnecessary data transmission, and also improves response times. With GraphQL, you won't have to deal with unexpected data being returned, which is particularly useful when building headless storefronts for Magento 2.