DEV Community

Cover image for How to Mock GraphQL API Responses 10x Faster
Anmol Baranwal Subscriber for Requestly

Posted on

How to Mock GraphQL API Responses 10x Faster

GraphQL has solved so many problems while fetching data using APIs.

Usually, the frontend developers have to wait for the backend team to update the APIs. This is one of the most useful cases when mocking a GraphQL request and it is super helpful.

Today, we will explore how Requestly can help you do that by reducing dependency on backend developers.

Let's jump in.

legendary gif


In a nutshell, we are covering these topics in detail.

  1. What is the usual workflow when APIs aren't available?
  2. How to Mock GraphQL APIs with Requestly.
  3. More brief on what Requestly can help you achieve.

Star Requestly ⭐


1. What is the usual workflow when APIs aren't available?

In most cases, there isn't an efficient way to implement a proper frontend without API logic.

backend is not ready

Typically, when APIs aren't ready, frontend developers rely on hardcoded responses based on API contracts.

These contracts are shared in JSON format, detailing the expected request and response structures.

While this allows them to move forward with UI development. This back-and-forth of removing and reintegrating hardcoded responses can lead to a disorganized codebase and is very time-consuming.

I've covered this problem in detail in one of the previous articles. You can read about it in the first section of below attached article.

 

✅ Instead of hardcoding responses, a simple solution for developers can be to use mock servers that simulate API responses. This allows for more dynamic testing and reduces the need to modify code repeatedly.

mock

Let's see how we can solve this problem in the next section!


2. How Requestly solves that problem including use cases.

If you've ever developed a website, you know that every app needs to make a call to the server to fetch its resources.

It can be API requests, scripts or anything else to render it on the webpage.

Requestly is an open source frontend development platform that helps developers test and debug their apps faster without needing multiple deployment cycles. It helps you to:

✅ Build features when backend API is not ready.

✅ Testing code changes in production without deployment cycles.

✅ Testing, Validating, Mocking API responses and many more.

frontend vs backend

 

🎯 How to install Requestly?

You can download the desktop app or find it on your preferred browser including Chrome, Safari and Brave.

requestly

desktop version

the desktop version

 

There are many other use cases like Requestly can help avoid the risk of accidentally committing mock code. But I will explore a single use case on how we can use it to update the response with production GraphQL APIs.

Requestly is open source with 2.3k stars on GitHub.

Star Requestly ⭐

 

Let's see how to change the response body of HTTP requests without making actual changes in the server content using the Requestly Response Rule.

First, let's create a new Rule to modify the response body of an HTTP request.

create new rule

create new rule

 

We will only look at modify the response rule.

Select the API response option

Select the API response option

 

You get various template options as well if you quickly want to get started.

various template options

You can also click the Help option and you will get a bunch of other resources to help you get started.

resources in help tab

 

🎯 What are GraphQL APIs and how are they different than REST APIs

Before trying to learn how to mock those, let's first understand what actually is GraphQL APIs.

GraphQL is a query language for APIs and provides an understandable description of the data in your API, giving clients the power to ask for exactly what they need and nothing more.

GraphQL APIs use a single endpoint for all the queries to the backend while on the other hand REST APIs have different endpoints for different resources.

The problem with usual APIs is:

-→ Underfetching : we may need multiple entities at one time in which case each request is underfetching the actual data we want.

underfetching

-→ Overfetching : it's a case where you are fetching too much data, meaning there is data in the response you don't use.

graphql vs rest api

You can learn more in this stackoverflow question - What is Over-Fetching or Under-fetching?

For instance, this can be one of the examples.

POST /graphql
{
  "operationName": "getUsers",
  "query": `
    query getUsers {
      users {
        id
        email
      }
    }
  `
}
Enter fullscreen mode Exit fullscreen mode

When this request is sent, the server responds with a list of users, each containing their id and email. An example response could be:

{
  "data": {
    "users": [
      { "id": "1", "email": "user1@example.com" },
      { "id": "2", "email": "user2@example.com" }
    ]
  }
}
Enter fullscreen mode Exit fullscreen mode

This type of query is much more efficient because it only retrieves the specific fields we need.

Under the hood, it's still the same old HTTP.

-→ 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}}

-→ POST REQUEST:

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

 

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

You can watch this video by Fireship to understand GraphQL APIs in 100 seconds.

 

🎯 Example using Medium GraphQL API Endpoints

As I told you before, GraphQL APIs use a single endpoint for all the queries which is not the case with REST APIs.

So targeting specific queries in GraphQL needs a filter based on operation or query. Requestly enables you to filter the API calls based on operation or query. Let's see how we can do that.

We will explore the option of GraphQL in the rule using the Medium API endpoints which are based on GraphQL, with two different examples.

graphQL API in Medium network log

graphQL API in Medium network log

 

There are many fetched requests which you can check out.

fetched requests

fetched requests

 

The API endpoint that's responsible is: medium.com/_/graphql.

-→ 🎯 Right sidebar tags.

As you know, they put up recommended tags on the sidebar so let's find the payload operation for that.

In GraphQL, the term payload operation typically refers to the data structure that is sent or received during a GraphQL request.
This includes the actual data being queried or mutated, as well as any additional metadata necessary for processing the request.

right sidebar query

You can also find all the info including operationName and graphQL API URL from the Requestly Network Inspector.

payload operation through requestly log

 

This is what the dashboard looks like with empty values.

GraphQL APIs Response rule

 

✅ Explanation.

-→ Request: this will contain the main API endpoint URL that will be used along with options like contains and equal.

-→ Key: The key is the JSON key in the request payload. It also supports nested paths. For instance, if the operation name is available at path data.operationName instead of root, the Key can be specified as data.operationName. In case the request body starts with an array like [{ "operationName": "value", ...}], the Key can be specified as 0.operationName.

-→ operationName: it is a meaningful and explicit name for your operation. It is only required in multi-operation documents, but its use is encouraged because it is very helpful for debugging and server-side logging.

-→ Response status: This will be the status code sent with the response that will help you identify the log easily. You can select the status codes like 3xx, 4xx, 5xx and many more depending on your case.

-→ Response: We can use static response data or a dynamic request to add custom logic using code. In case of lengthy API calls or the need to manage multiple requests simultaneously, using Async/Await can be efficient. It's damn useful :)

 

Let's set up a rule with the necessary values. It's important to use the same value RightSidebarQuery as highlighted in the payload snapshot.

0.operationName is also based on the Payload array structure in the previous snapshot (network log). We are using the filter option of Equals to make our rule very strict.

rule

 

Change the JSON response including the first two tags.

updated JSON response for the tags

You can copy this response from this gist on GitHub.

 

Output.

As you can see, a message will be displayed on the page that the rule has been applied.

tags are modified

tags are modified as per JSON response

 

-→ 🎯 Recommended feed post.

You can see the Payload operation for this in the below network log.

payload operation

 

Similar to sidebar tags, we can fill up the necessary values for this rule.

rule for inline recommended post query

You can copy this response from this gist on GitHub.

 

As you can see, I've updated the JSON response of the title and subtitle to check the output.

It's working fine as per the rule!

working fine

 

There is also an option to serve the response without making a call to the server. In that case, requestly will directly serve the response and it won't show in the network log.

response

You can read more on the docs and official blog on how to Mock GraphQL APIs Response.

Or watch this video!


3. More brief on what Requestly can help you achieve.

You can lots of other stuff like:

-→ Testing scripts or APIs directly on staging/production sites by redirecting HTTP requests(API Calls/Files) from one environment to another.

redirect

 

-→ Modify headers or Inject custom scripts/styles on external web pages.

-→ Intercept, Modify, and Mock GraphQL Query by applying extra targeting on operation name and query data.

 

It's extremely useful for QA Software engineers or frontend teams. Let's see some of the exciting features:

✅ You can also do API development & testing using the API client of Requestly. You can even bypass CORS Issues and it's available at app.requestly.io/api-client.

api client

api client dashboard

api client empty dashboard

 

✅ You can inspect your HTTPs requests and responses in plain text with just one click. A lot of advanced filters such as Content-Type, Status Code, and Method are available to precisely search what you need. You can create mocks for the complete flow as well.

http traffic

 

✅ You can export or import the rules, and mocks as JSON.

import rules

import the rules

 

export rules

you can share any rule and you will get the option to download it

 

✅ You can create a workspace to share rules, mocks, and sessions. Faster collaboration leads to solving problems quickly.

collaboration

 

✅ You can record sessions and it's automatically done whenever you test a rule from the dashboard.

sessions

 

✅ You can enable/disable rules from the dashboard.

disable or enable rules

 

✅ You can read the documentation on how they perform in comparison with competitive tools like Charles Proxy, Fiddler, Resource Override, ModHeader, HTTP Toolkit, Proxyman, Wireshark, Mockoon, BirdEatsBug and Jam.

comparison

 

You can follow the quickstart guide and read how to guides which would answer most of your questions.

I also recommend watching this quick demo to get started with Requestly!

 

For the next article, we are covering on how to Record HTTP Traffic and create Mocks for the complete flow. Stay tuned!


I think it's safe to say Requestly provides the easiest way to mock the response of GraphQL APIs.

Around 250k+ frontend developers are already using Requestly which makes them very credible.

Let me know if you've any questions or feedback.

Have a great day. Till next time!

If you like this kind of stuff,
please follow me for more :)
profile of Twitter with username Anmol_Codes profile of GitHub with username Anmol-Baranwal profile of LinkedIn with username Anmol-Baranwal

Follow Requestly for more content like this.

Top comments (1)

Collapse
 
anmolbaranwal profile image
Anmol Baranwal

If you're looking to mock REST APIs, I have covered that in another article.

I have used examples from Wikipedia and Amazon search. You will love it!

rest apis

I kept these separate so it's easier to read.