Q5 of 20 · GraphQL

Why should dynamic values go in variables rather than be interpolated into the query string?

GraphQLMidgraphqlvariablessecurityapi

Short answer

Short answer: Variables keep the query static and the data separate — like parameterised SQL. String-interpolating user input into a query is an injection risk and breaks caching and validation. Test that the API accepts properly-typed variables and rejects malformed ones.

Detail

A GraphQL request separates the query text from its inputs:

{
  "query": "query GetUser($id: ID!) { user(id: $id) { name } }",
  "variables": { "id": "42" }
}

Why variables matter — the same reasoning as parameterised SQL statements:

  • Security: interpolating raw input into the query string is an injection vector; variables are passed as typed, separate data.
  • Type safety: $id: ID! is validated against the schema before execution — a wrong type is rejected up front.
  • Caching / persisted queries: a static query string with separate variables can be cached or allow-listed; a string rebuilt per request can't.

Testing angle: send a well-typed variable and assert success; send a wrong-typed or missing non-null variable and assert a validation error. The injection-resistance is also worth a negative security test.

// WHAT INTERVIEWERS LOOK FOR

The parameterised-SQL analogy, the injection/type-safety reasoning, and a negative test for wrong-typed variables.