</>

Technology

Rest Assured

Difficulty

Advanced

Interview Question

What is GraphQL and how is it different from REST APIs?

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

CODE
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

GRAPHQL
# 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

FeatureRESTGraphQL
EndpointsMultiple (/users, /posts)Single (/graphql)
Data fetchingFixed — server decidesFlexible — client decides
Over-fetchingCommonEliminated
Under-fetchingCommon (N+1 problem)Eliminated
VersioningURL versioning (/v1, /v2)No versioning needed
HTTP methodGET, POST, PUT, DELETEUsually POST
Response formatJSONJSON
Learning curveLowMedium
CachingEasy (HTTP cache)Harder (POST requests)

Testing GraphQL with Rest Assured

Java
@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)

Java
@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."

Follow AutomateQA

Related Topics