Answer
GraphQL vs REST
GraphQL is a query language for APIs and a runtime for fulfilling those queries. Unlike REST which has multiple endpoints, GraphQL has a single endpoint where clients specify exactly what data they need.
REST API — Fixed Endpoints, Fixed Data
GET /api/users/1 → Returns ALL user fields
GET /api/users/1/posts → Separate request needed for posts
GET /api/users/1/friends → Yet another request for friends
Problems:
- ✓Over-fetching: Gets all fields even if you only need name
- ✓Under-fetching: Need multiple requests to get related data
- ✓N+1 problem: 10 users = 1 + 10 = 11 requests for their posts
GraphQL — Single Endpoint, Precise Data
# Get ONLY what you need in ONE request
query {
user(id: 1) {
name
email
posts {
title
createdAt
}
friends {
name
}
}
}
One request returns exactly: name, email, posts, and friends.
GraphQL vs REST Comparison
| Feature | REST | GraphQL |
|---|---|---|
| Endpoints | Multiple (/users, /posts) | Single (/graphql) |
| Data fetching | Fixed — server decides | Flexible — client decides |
| Over-fetching | Common | Eliminated |
| Under-fetching | Common (N+1 problem) | Eliminated |
| Versioning | URL versioning (/v1, /v2) | No versioning needed |
| HTTP method | GET, POST, PUT, DELETE | Usually POST |
| Response format | JSON | JSON |
| Learning curve | Low | Medium |
| Caching | Easy (HTTP cache) | Harder (POST requests) |
Testing GraphQL with Rest Assured
@Test
public void testGraphQLQuery() {
String query = """
{
"query": "{ user(id: 1) { name email } }"
}
""";
given()
.contentType(ContentType.JSON)
.header("Authorization", "Bearer " + token)
.body(query)
.when()
.post("/graphql")
.then()
.statusCode(200)
.body("data.user.name", equalTo("John"))
.body("data.user.email", equalTo("john@example.com"))
.body("errors", nullValue()); // No errors means success
}
Testing GraphQL Mutations (Create/Update/Delete)
@Test
public void testGraphQLMutation() {
String mutation = """
{
"query": "mutation { createUser(name: \\"Jane\\", email: \\"jane@test.com\\") { id name } }"
}
""";
given()
.contentType(ContentType.JSON)
.body(mutation)
.when()
.post("/graphql")
.then()
.statusCode(200)
.body("data.createUser.id", notNullValue())
.body("data.createUser.name", equalTo("Jane"));
}
In Interviews
"GraphQL solves REST's over-fetching and under-fetching problems by letting the client specify exactly what data it needs. REST is simpler and better for public APIs and caching. GraphQL is better for complex, data-heavy applications like Facebook, GitHub, or Shopify where clients have varying data needs."
