How to Mock and Fake GraphQL APIs using Chrome Extension

				
					{
  "data": { ... },
  "extensions": { ... }
}
				
			

Graphql has completely changed the way APIs are used to fetch data.

But what should a front-end developer do when he is waiting on the backend team for the API to update? This is one of the most common cases when mocking a GraphQL request is helpful.

We have tried to solve this by using a Chrome Extension that can effectively target GraphQL queries. Using simple rules you can modify and provide custom data to your GraphQL requests, without making any changes to the code.

How GraphQL really works?

GraphQL might seem like a new way to make API request, but under the hood it uses old basic HTTP.

A GraphQL request can be sent in one of two ways:

  1. GET request
    If GraphQL is sent using a GET request, the GraphQL query string is passed in as search parameters to the endpoint.

    Example URL: http://domain.com/graphql_endpoint?query={hero{name}}

  2. POST request
    In case of the POST request, the query string, variables and even oprerationName are passed in the request body as payload.

Regardless of the method used, the response always follows a common format. The server returns a json object.

All responses, including errors, always return HTTP 200 OK status codes.
The response is a JSON map including the fields “data”, “errors”, or “extensions” following the GraphQL specification.

They follow the following formats. Successful queries are in the following format:

The “data” field contains the result of your GraphQL request. The response has exactly the same shape as the result.

Suppose you have a GraphQL query to fetch user information, like the user’s name and email. The query might look something like this:

				
					query {
  user(id: "123") {
    name
    email
  }
}

				
			

The response to this query will typically be structured in JSON format, with a data field that contains the results of the query.

For example:

				
					{
  "data": {
    "user": {
      "name": "Alice Johnson",
      "email": "alice.johnson@example.com"
    }
  }
}

				
			

In this response:

  • The top-level data field encapsulates the result of the query.
  • Inside data, there’s a user field that corresponds to the user query in the request.
  • The user field then contains the requested fields, name and email, with their respective values.

How to override the GraphQL response body

We can use Requestly chrome extension to specifically target GraphQL queries and modify the result that they return using the Modify Response Rule

In GraphQL, there is typically just one HTTP endpoint for all client interactions. And to specify which operation to execute, it is a common practice to pass operationName in the request payload.
 
For example,

				
					POST /graphql
{
  "operationName": "getUsers",
  "query": `
    query getUsers {
      users {
        id
        email
      }
    }
  `
}
				
			

To modify response of a GraphQL request, you may create a Modify API Response rule and target operationName field in the request payload.

Select Resource Type as GraphQL API and in GraphQL Operation (Request Payload Filter) enter

  • key as operationName
  • value as getUsers

If your GraphQL request does not specify operationName, you should select Resource Type as REST API and use Dynamic (JavaScript) mode to filter the request and override the response.
For example, in the below GraphQL request, there is no operationName field. The operation getUsers is instead specified in query field.
				
					POST /graphql
{
  "query": `
    query getUsers {
      users {
        id
        email
      }
    }
  `
}
				
			
The JavaScript code would look like:
				
					function modifyResponse(args) {
  const {url, response, requestData, responseJSON} = args;

  if (requestData.query?.includes("query getUsers")) {
    // return custom response from this query
    console.log("Requestly: Modifying response", { query: requestData.query });
    return {...responseJSON, custom: true};
  }

  // return original response
  return response;
}
				
			

How to override the GraphQL request payload

You can create a Modify Request Body rule in Requestly to alter the GraphQL query or variables.

This is done by changing the request payload, which allows you to modify the query string or variables in the request body.

The JavaScript function modifyRequestBody receives arguments like method, url, body, and bodyAsJson, and you can use these to tailor your modifications.

 

In this article we have learnt how we can modify or mock the request payload and response body of GraphQL requests. While GraphQL is one of the most popular use-case of Requestly, it can help modify any type of HTTP request.

Hope it helps.

This article was written by:

Picture of Sagar Soni

Sagar Soni

Sagar is the co-founder and CTO of Requestly. When he's not busy architecting the next big thing in software development, you'll likely find him behind the wheel, cruising the streets and enjoying the thrill of the drive. For Sagar, it's all about the code by day and the open road by night.

Share this article:

You may also like