GraphQL
GraphQL Interview Questions & Answers (Beginner → Advanced)
SECTION 1 – GraphQL Fundamentals (Q1–Q10)
Q1. What is GraphQL and why do modern companies prefer it over REST?
Explanation:
GraphQL is a query language and runtime for APIs developed by Facebook. Instead of multiple REST endpoints, GraphQL exposes a single endpoint where clients request exactly the data they need. This avoids over‑fetching and under‑fetching. Companies prefer GraphQL because it improves performance, reduces payload size, and gives frontend teams more flexibility. It also provides strong typing and built‑in documentation through schema.
Syntax:
query { users { id name } }
Example:
query {
users {
id
name
}
}
Interview Tip:
Say clearly: GraphQL = single endpoint + client controls data shape.
Q2. Explain the core building blocks of GraphQL.
Explanation:
GraphQL mainly consists of Schema, Queries, Mutations, and Resolvers. The schema defines available data types and operations. Queries fetch data, mutations modify data, and resolvers contain business logic. This separation makes GraphQL structured and scalable. Enterprise systems rely heavily on schema‑first development.
Syntax:
type User { id: ID! name: String }
Example:
type Query {
users: [User]
}
Interview Tip:
Always mention Schema → Query → Resolver flow.
Q3. What is a GraphQL Schema?
Explanation:
Schema is the contract between client and server. It defines types, relationships, and operations. GraphQL servers validate every request against schema. This prevents invalid API calls and improves developer confidence. Large companies treat schema as API documentation.
Syntax:
type User { id: ID! name: String }
Example:
type Query {
getUser(id: ID!): User
}
Interview Tip:
Schema is mandatory in GraphQL.
Q4. What is a Query in GraphQL?
Explanation:
Query is used to read data from server. It is similar to GET in REST. Clients specify exactly which fields they want. This avoids unnecessary data transfer and improves performance.
Syntax:
query { field }
Example:
query {
getUser(id: "1") {
name
email
}
}
Interview Tip:
Queries never change server state.
Q5. What is a Mutation in GraphQL?
Explanation:
Mutations are used to create, update, or delete data. They are equivalent to POST/PUT/DELETE in REST. Mutations can return updated objects, making frontend synchronization easier.
Syntax:
mutation { createUser(...) }
Example:
mutation {
createUser(name:"Sumit") {
id
name
}
}
Interview Tip:
Mutations modify server state.
Q6. What are Resolvers?
Explanation:
Resolvers are functions that fetch actual data for fields. Each schema field maps to a resolver. They connect GraphQL to databases or services. Without resolvers, schema cannot return data.
Syntax:
Query: { users: () => db.users }
Example:
const resolvers = {
Query: {
users: () => User.find()
}
}
Interview Tip:
Resolvers contain business logic.
Q7. What is ID type in GraphQL?
Explanation:
ID represents unique identifiers. It is serialized as string. IDs help cache and normalize data. Most companies use ID for primary keys.
Syntax:
id: ID!
Example:
type User { id: ID! }
Interview Tip:
ID is not integer; it is opaque.
Q8. Difference between GraphQL and REST.
Explanation:
REST uses multiple endpoints while GraphQL uses one. REST responses are fixed, GraphQL responses are flexible. GraphQL reduces network calls and supports strong typing. REST requires versioning; GraphQL evolves schema.
Example:
REST: /users /posts
GraphQL: /graphql
Interview Tip:
Focus on over‑fetching problem.
Q9. What is Playground / GraphiQL?
Explanation:
GraphQL Playground is an IDE to test queries. It provides auto‑completion and schema exploration. Developers use it for debugging APIs.
Example:
query { users { name } }
Interview Tip:
Mention built‑in documentation.
Q10. What is JSON in GraphQL responses?
Explanation:
GraphQL always returns JSON. This makes frontend integration simple. JSON structure matches query shape exactly. Enterprises prefer this predictability.
Example:
{ "data": { "users": [] } }
Interview Tip:
Response mirrors query.
SECTION 2 – Schema Design & Types (Q11–Q25)
Q11. What are Scalar Types in GraphQL and why are they important?
Explanation:
Scalar types represent primitive values that cannot be broken into smaller fields. GraphQL provides default scalars such as Int, Float, String, Boolean, and ID. These form the foundation of every schema. Scalars ensure data consistency and validation at API level. In enterprise systems, scalars prevent invalid client inputs before hitting business logic. Custom scalars can also be created for Date, Email, or Phone.
Syntax:
age: Int
name: String
Example:
type User {
id: ID!
name: String
age: Int
}
Interview Tip:
Always mention default + custom scalars.
Q12. What are Custom Scalars and when should they be used?
Explanation:
Custom scalars allow you to define your own primitive types such as Date, URL, or Email. They are useful when built-in scalars are not enough. Validation logic lives inside the scalar resolver. Large companies use custom scalars to standardize formats across microservices. This avoids repeated validation in every resolver.
Syntax:
scalar Date
Example:
scalar Date
type User {
createdAt: Date
}
Interview Tip:
Use custom scalars for validation and consistency.
Q13. What are Enums in GraphQL?
Explanation:
Enums restrict field values to a predefined list. This prevents invalid input from clients. Enums improve readability and documentation. Enterprise APIs use enums for roles, statuses, and categories. They act like constants shared between frontend and backend.
Syntax:
enum Role { ADMIN USER }
Example:
type User {
role: Role
}
Interview Tip:
Enums enforce allowed values.
Q14. What are Input Types and why are they needed?
Explanation:
Input types define structured data for mutations. GraphQL does not allow object types as inputs, so Input types are required. They improve validation and maintain clean APIs. In production systems, input types act as DTOs (Data Transfer Objects). They also simplify versioning.
Syntax:
input UserInput { name: String }
Example:
mutation createUser($data: UserInput!)
Interview Tip:
Inputs are mandatory for complex mutations.
Q15. What is Non-Null (!) operator?
Explanation:
The exclamation mark makes a field mandatory. It guarantees that value will never be null. If server fails to return it, GraphQL throws error. This improves contract reliability. Enterprises use Non-Null to enforce critical fields like IDs.
Syntax:
id: ID!
Example:
type User { id: ID! }
Interview Tip:
Non-null strengthens API contracts.
Q16. What are Lists in GraphQL?
Explanation:
Lists represent collections of items. They are written using square brackets. Lists can also be combined with Non-Null for strict rules. Companies use lists for pagination and relationships. Understanding list nullability is critical in interviews.
Syntax:
users: [User]
Example:
type Query { users: [User!]! }
Interview Tip:
Explain list + nullability.
Q17. What are Interfaces in GraphQL?
Explanation:
Interfaces define common fields shared by multiple types. They support polymorphism. This is useful when different objects have similar structure. Enterprise APIs use interfaces for search results or activity feeds.
Syntax:
interface Node { id: ID! }
Example:
type User implements Node { id: ID! name: String }
Interview Tip:
Interfaces enable polymorphism.
Q18. What are Unions in GraphQL?
Explanation:
Unions allow a field to return multiple unrelated types. Unlike interfaces, unions share no common fields. They are commonly used in search APIs. Clients must use fragments to handle responses.
Syntax:
union SearchResult = User | Post
Example:
search(text:String): [SearchResult]
Interview Tip:
Union = multiple types, no shared fields.
Q19. What are Fragments and why are they useful?
Explanation:
Fragments allow reuse of field selections. They reduce duplication and improve maintainability. Frontend teams rely heavily on fragments. Enterprises use fragments to standardize UI queries.
Syntax:
fragment UserFields on User
Example:
fragment UserFields on User { id name }
Interview Tip:
Fragments = reusable query parts.
Q20. What are Query Variables?
Explanation:
Variables allow dynamic values in queries. They improve security and caching. Instead of hardcoding IDs, variables are passed separately. Production APIs always use variables.
Syntax:
query ($id:ID!)
Example:
query GetUser($id:ID!) { getUser(id:$id){name} }
Interview Tip:
Variables prevent query injection.
Q21. What are Aliases?
Explanation:
Aliases rename fields in response. They allow same field to be queried multiple times. Used heavily in dashboards. Prevents naming collisions.
Example:
user1:getUser(id:"1")
Interview Tip:
Aliases rename response fields.
Q22. What are Directives?
Explanation:
Directives modify query execution. Common directives are @include and @skip. They add conditional logic at query level. Enterprises use directives for feature flags.
Syntax:
@include(if:true)
Interview Tip:
Directives control execution flow.
Q23. How does pagination work in GraphQL?
Explanation:
Pagination limits large datasets. Offset or cursor based methods are used. Cursor pagination is preferred in production. It improves performance and consistency.
Interview Tip:
Cursor pagination is best practice.
Q24. How are relationships modeled in GraphQL?
Explanation:
Relations are defined via nested types. Parent resolver fetches child data. DataLoader is used to avoid N+1 problem. Enterprises rely on this pattern.
Interview Tip:
Mention N+1 prevention.
Q25. What is Schema-first vs Code-first?
Explanation:
Schema-first writes schema first. Code-first generates schema from code. Both are used in companies. Schema-first preferred for large teams.
Interview Tip:
Big companies favor schema-first.
SECTION 3 – Backend Integration (Q26–Q40)
Q26. How do you integrate GraphQL with Node.js backend?
Explanation:
GraphQL is commonly integrated with Node.js using Apollo Server or Express GraphQL. The backend exposes a single /graphql endpoint. Schema defines API structure while resolvers connect to databases or services. This architecture separates API contract from business logic. Most enterprises combine GraphQL with Express or Fastify for middleware support.
Syntax:
const { ApolloServer } = require('apollo-server');
Example:
const server = new ApolloServer({ typeDefs, resolvers });
server.listen();
Interview Tip:
Mention Apollo + Express integration.
Q27. What is Apollo Server and why is it widely used?
Explanation:
Apollo Server is a popular GraphQL server implementation. It provides schema management, playground, caching, and authentication support. It integrates easily with Node.js frameworks. Large companies prefer Apollo because of ecosystem maturity and federation support.
Syntax:
new ApolloServer()
Example:
const server = new ApolloServer({ typeDefs, resolvers });
Interview Tip:
Apollo = production ready GraphQL server.
Q28. How do resolvers connect to MongoDB or SQL databases?
Explanation:
Resolvers act as bridge between GraphQL and database. Inside resolver functions, database queries are executed. MongoDB uses Mongoose while SQL uses ORM like Prisma or Sequelize. This keeps API layer independent from storage layer.
Syntax:
User.find()
Example:
Query:{ users:()=>User.find() }
Interview Tip:
Resolvers = data access layer.
Q29. What is Context in GraphQL?
Explanation:
Context is shared object passed to every resolver. It usually contains authenticated user, database connections, and request headers. Context avoids passing parameters manually. Enterprises use context for authorization and logging.
Syntax:
context:({req})=>({ user:req.user })
Example:
new ApolloServer({ context })
Interview Tip:
Context carries auth data.
Q30. How is Authentication implemented in GraphQL?
Explanation:
Authentication is done using JWT tokens or sessions. Token is sent via headers. Middleware verifies token and stores user in context. Resolvers then access authenticated user. This pattern is used in most production systems.
Syntax:
Authorization: Bearer token
Example:
context:({req})=>verifyToken(req.headers.authorization)
Interview Tip:
Auth handled before resolvers.
Q31. How does Authorization work in GraphQL?
Explanation:
Authorization checks user permissions. Implemented inside resolvers or middleware. Role-based access is common. Large systems use directive-based authorization. Prevents unauthorized data exposure.
Example:
if(user.role!=='ADMIN') throw Error()
Interview Tip:
AuthN ≠ AuthZ.
Q32. What is Middleware in GraphQL?
Explanation:
Middleware executes before or after resolvers. Used for logging, auth, validation. Apollo supports plugins. Middleware improves separation of concerns.
Interview Tip:
Middleware wraps resolvers.
Q33. What is N+1 Problem?
Explanation:
Occurs when nested queries trigger multiple DB calls. Example: fetching users then posts individually. This causes performance issues. DataLoader batches requests to solve it.
Interview Tip:
Always mention DataLoader.
Q34. What is DataLoader?
Explanation:
DataLoader batches and caches database calls per request. Prevents N+1 problem. Developed by Facebook. Essential for performance optimization.
Example:
new DataLoader(keys=>batchFn(keys))
Interview Tip:
DataLoader = batching + caching.
Q35. How is Pagination handled in GraphQL backend?
Explanation:
Pagination limits large datasets. Cursor-based pagination is preferred. Backend returns edges and cursors. This ensures consistency with real-time data.
Interview Tip:
Cursor pagination is production standard.
Q36. How is Error Handling done?
Explanation:
Errors are returned in errors array. Apollo provides formatError. Custom error classes improve debugging. Enterprises standardize error responses.
Example:
throw new ApolloError('Not Found')
Interview Tip:
Errors never crash server.
Q37. How do you integrate REST APIs with GraphQL?
Explanation:
Resolvers can call REST APIs. Apollo RESTDataSource simplifies this. This allows gradual migration from REST to GraphQL.
Interview Tip:
GraphQL can wrap REST.
Q38. What is Caching in GraphQL?
Explanation:
Caching improves performance. Apollo supports response caching. Redis is used in production. Cache reduces database load.
Interview Tip:
Mention Redis.
Q39. How do you secure GraphQL APIs?
Explanation:
Security includes depth limiting, query complexity, auth, rate limiting. Prevents DoS attacks. Production systems enforce query limits.
Interview Tip:
Depth limit prevents abuse.
Q40. How do you deploy GraphQL backend?
Explanation:
GraphQL servers run in Docker containers. Deployed on AWS, Azure, or GCP. CI/CD pipelines automate builds. Monitoring tools track performance.
Interview Tip:
Mention Docker + cloud.
End of Section 3.