How to Mock GraphQL API Responses 10x Faster
Anmol Baranwal
Posted on October 4, 2024
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.
In a nutshell, we are covering these topics in detail.
- What is the usual workflow when APIs aren't available?
- How to Mock GraphQL APIs with Requestly.
- More brief on what Requestly can help you achieve.
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.
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.
How to Build Frontend Apps 10x Faster
Anmol Baranwal for Requestly ・ Sep 5
✅ 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.
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.
🎯 How to install Requestly?
You can download the desktop app or find it on your preferred browser including Chrome, Safari and Brave.
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.
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.
We will only look at modify the response rule.
You get various template options as well if you quickly want to get started.
You can also click the Help option and you will get a bunch of other resources to help you get started.
🎯 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.
-→ Overfetching
: it's a case where you are fetching too much data, meaning there is data in the response you don't use.
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
}
}
`
}
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" }
]
}
}
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.
There are many fetched requests which you can check out.
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.
You can also find all the info including operationName
and graphQL API URL
from the Requestly Network Inspector.
This is what the dashboard looks like with empty values.
✅ 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.
Change the JSON response including the first two 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.
-→ 🎯 Recommended feed post.
You can see the Payload operation for this in the below network log.
Similar to sidebar tags, we can fill up the necessary values for this rule.
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!
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.
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.
-→ 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.
✅ 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.
✅ You can export or import the rules, and mocks as JSON.
✅ You can create a workspace to share rules, mocks, and sessions. Faster collaboration leads to solving problems quickly.
✅ You can record sessions and it's automatically done whenever you test a rule from the dashboard.
✅ You can enable/disable rules from the dashboard.
✅ 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.
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!
Follow Requestly for more content like this.
Posted on October 4, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.