GraphQL Documentation
Ask an API for exactly the data you need — schemas, queries, mutations and resolvers.
GraphQL is a query language for APIs created at Facebook. Instead of many REST endpoints that return fixed data, a GraphQL API exposes one endpoint and a typed schema; the client asks for exactly the fields it needs — no more (over-fetching), no less (under-fetching). GitHub, Shopify, Netflix and many mobile apps use it.
1. Introduction & Setup
A GraphQL API has three parts:
- Schema — the types and operations available (written in SDL, the Schema Definition Language).
- Resolvers — functions that fetch the data for each field.
- Operations — queries (read), mutations (write) and subscriptions (real-time) sent by clients.
Set up a server with Node.js and Apollo Server:
mkdir graphql-api && cd graphql-api
npm init -y
npm install @apollo/server graphql
node index.js # then open http://localhost:4000 (Apollo Sandbox to try queries)
Every example on this page uses this schema and data:
# Sample schema: a small course platform
type Course {
id: ID!
title: String!
level: Level!
price: Float!
teacher: Teacher!
lessons(limit: Int): [Lesson!]!
}
type Teacher {
id: ID!
name: String!
courses: [Course!]!
}
type Lesson {
title: String!
minutes: Int!
}
enum Level {
BEGINNER
ADVANCED
}
input NewCourse {
title: String!
level: Level!
price: Float = 0
teacherId: ID!
}
type Query {
courses(level: Level): [Course!]!
course(id: ID!): Course
teachers: [Teacher!]!
}
type Mutation {
addCourse(input: NewCourse!): Course!
}
// index.js — data + resolvers (Apollo Server)
import { ApolloServer } from "@apollo/server";
import { startStandaloneServer } from "@apollo/server/standalone";
import fs from "node:fs";
const teachers = [
{ id: "t1", name: "Striver" },
{ id: "t2", name: "Hitesh" },
];
const courses = [
{ id: "c1", title: "DSA in C++", level: "ADVANCED", price: 0, teacherId: "t1",
lessons: [{ title: "Arrays", minutes: 45 }, { title: "Graphs", minutes: 70 }, { title: "DP", minutes: 90 }] },
{ id: "c2", title: "JavaScript Basics", level: "BEGINNER", price: 499, teacherId: "t2",
lessons: [{ title: "Variables", minutes: 20 }, { title: "Functions", minutes: 35 }] },
{ id: "c3", title: "React Projects", level: "ADVANCED", price: 999, teacherId: "t2", lessons: [] },
];
const resolvers = {
Query: {
courses: (_, { level }) => (level ? courses.filter((c) => c.level === level) : courses),
course: (_, { id }) => courses.find((c) => c.id === id) ?? null,
teachers: () => teachers,
},
Mutation: {
addCourse: (_, { input }) => {
const course = { id: `c${courses.length + 1}`, lessons: [], ...input };
courses.push(course);
return course;
},
},
Course: {
teacher: (course) => teachers.find((t) => t.id === course.teacherId),
lessons: (course, { limit }) => (limit ? course.lessons.slice(0, limit) : course.lessons),
},
Teacher: {
courses: (teacher) => courses.filter((c) => c.teacherId === teacher.id),
},
};
const typeDefs = fs.readFileSync("schema.graphql", "utf8");
const server = new ApolloServer({ typeDefs, resolvers });
const { url } = await startStandaloneServer(server, { listen: { port: 4000 } });
console.log(`GraphQL API ready at ${url}`);
⚠️ Common error:
Cannot use import statement outside a module— add"type": "module"topackage.json.
2. Basic Query Syntax
A query mirrors the shape of the JSON you get back.
query {
courses {
title
price
}
}
Output:
{
"data": {
"courses": [
{ "title": "DSA in C++", "price": 0 },
{ "title": "JavaScript Basics", "price": 499 },
{ "title": "React Projects", "price": 999 }
]
}
}
Clients send operations as an HTTP POST with a JSON body:
curl -X POST http://localhost:4000/ \
-H "Content-Type: application/json" \
-d '{"query": "{ courses { title price } }"}'
⚠️ Common error: asking for an object field without choosing sub-fields (
courses { teacher }) — GraphQL needs you to select scalar fields inside every object:teacher { name }.
3. Types & Schema
| Kind | Example |
|---|---|
| Scalars | Int, Float, String, Boolean, ID (+ custom scalars like DateTime) |
| Object types | type Course { ... } |
| Non-null | String! — never null |
| Lists | [Lesson!]! — non-null list of non-null lessons |
| Enums | enum Level { BEGINNER ADVANCED } |
| Input types | input NewCourse { ... } — for arguments |
| Interfaces / unions | shared fields / "one of these types" |
Ask the server about its own schema (introspection — how tools like GraphiQL autocomplete):
query {
__type(name: "Level") {
enumValues {
name
}
}
}
{
"data": {
"__type": {
"enumValues": [
{ "name": "BEGINNER" },
{ "name": "ADVANCED" }
]
}
}
}
4. Arguments & Variables
Fields can take arguments:
query {
course(id: "c1") {
title
lessons(limit: 2) {
title
minutes
}
}
}
{
"data": {
"course": {
"title": "DSA in C++",
"lessons": [
{ "title": "Arrays", "minutes": 45 },
{ "title": "Graphs", "minutes": 70 }
]
}
}
}
Real clients never paste values into the query string — they use variables (safer and cacheable):
query CoursesByLevel($level: Level) {
courses(level: $level) {
id
title
}
}
{ "level": "ADVANCED" }
Result:
{
"data": {
"courses": [
{ "id": "c1", "title": "DSA in C++" },
{ "id": "c3", "title": "React Projects" }
]
}
}
⚠️ Common error:
Variable "$level" of type "String" used in position expecting type "Level"— declare variables with the exact schema type.
5. Nested Queries (Relationships)
One request can follow relationships that would need several REST calls:
query {
teachers {
name
courses {
title
teacher {
name
}
}
}
}
{
"data": {
"teachers": [
{
"name": "Striver",
"courses": [
{ "title": "DSA in C++", "teacher": { "name": "Striver" } }
]
},
{
"name": "Hitesh",
"courses": [
{ "title": "JavaScript Basics", "teacher": { "name": "Hitesh" } },
{ "title": "React Projects", "teacher": { "name": "Hitesh" } }
]
}
]
}
}
Each field's resolver receives the parent object (Course.teacher gets the course) — that's how the graph is walked.
6. Aliases, Fragments & Directives
Aliases rename fields (and let you query the same field twice):
query {
beginner: courses(level: BEGINNER) {
title
}
advanced: courses(level: ADVANCED) {
title
}
}
{
"data": {
"beginner": [{ "title": "JavaScript Basics" }],
"advanced": [{ "title": "DSA in C++" }, { "title": "React Projects" }]
}
}
Fragments reuse a set of fields; directives @include(if:) / @skip(if:) toggle fields:
fragment CourseCard on Course {
title
price
}
query Card($withTeacher: Boolean!) {
course(id: "c2") {
...CourseCard
teacher @include(if: $withTeacher) {
name
}
}
}
{ "withTeacher": true }
Result:
{
"data": {
"course": {
"title": "JavaScript Basics",
"price": 499,
"teacher": { "name": "Hitesh" }
}
}
}
7. Mutations
Mutations change data and return the result — so the client gets fresh data in the same request.
mutation AddCourse($input: NewCourse!) {
addCourse(input: $input) {
id
title
price
teacher {
name
}
}
}
{ "input": { "title": "Node.js APIs", "level": "BEGINNER", "teacherId": "t2" } }
Result:
{
"data": {
"addCourse": {
"id": "c4",
"title": "Node.js APIs",
"price": 0,
"teacher": { "name": "Hitesh" }
}
}
}
(price used the default value 0 from the NewCourse input type.)
⚠️ Common error: using
queryfor something that changes data. Usemutation— top-level mutation fields run in order, query fields may run in parallel.
8. Errors & Nullability
GraphQL usually returns HTTP 200 with an errors array; partial data can still be returned.
query {
course(id: "c99") {
title
}
}
{
"data": {
"course": null
}
}
course is nullable (Course), so a missing course is simply null. Validation errors (unknown fields, wrong types) are reported before anything runs:
query {
courses {
rating
}
}
{
"errors": [
{
"message": "Cannot query field \"rating\" on type \"Course\".",
"locations": [{ "line": 3, "column": 5 }]
}
]
}
Throw errors from resolvers (e.g. throw new GraphQLError("Not allowed", { extensions: { code: "FORBIDDEN" } })) for auth and validation failures.
9. Server Concepts: Context, Auth & the N+1 Problem
Context is shared by all resolvers in one request — use it for the logged-in user and data loaders:
const { url } = await startStandaloneServer(server, {
context: async ({ req }) => {
const token = req.headers.authorization?.replace("Bearer ", "");
const user = token ? await verifyJwt(token) : null;
return { user, loaders: createLoaders() };
},
});
// in a resolver
addCourse: (_, { input }, { user }) => {
if (!user || user.role !== "teacher") throw new GraphQLError("Not allowed", { extensions: { code: "FORBIDDEN" } });
return db.courses.create({ ...input, teacherId: user.id });
},
The N+1 problem — listing 100 courses and resolving teacher for each can trigger 100 extra database queries. DataLoader batches and caches them into one query per request:
import DataLoader from "dataloader";
const createLoaders = () => ({
teacher: new DataLoader(async (ids) => {
const rows = await Teacher.find({ _id: { $in: ids } });
return ids.map((id) => rows.find((t) => String(t._id) === String(id))); // same order as ids
}),
});
// Course.teacher resolver
teacher: (course, _, { loaders }) => loaders.teacher.load(course.teacherId),
⚠️ Common error: unbounded queries — clients can request deeply nested data and overload the server. Add pagination arguments, query depth/complexity limits and timeouts.
10. Advanced Concepts
Pagination — cursor-based "connections" (Relay style) are the common pattern:
type CourseConnection {
edges: [CourseEdge!]!
pageInfo: PageInfo!
}
type CourseEdge { cursor: String! node: Course! }
type PageInfo { hasNextPage: Boolean! endCursor: String }
type Query {
coursesPage(first: Int!, after: String): CourseConnection!
}
Interfaces and unions:
interface Node { id: ID! }
type Video implements Node { id: ID! url: String! }
type Article implements Node { id: ID! words: Int! }
union SearchResult = Video | Article
query {
search(text: "graphs") {
__typename
... on Video { url }
... on Article { words }
}
}
Subscriptions push real-time updates over WebSockets:
subscription {
courseAdded {
title
}
}
Clients — Apollo Client (React), urql, Relay, or plain fetch:
const res = await fetch("http://localhost:4000/", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
query: "query ($id: ID!) { course(id: $id) { title price } }",
variables: { id: "c1" },
}),
});
const { data, errors } = await res.json();
// React with Apollo Client
const GET_COURSES = gql`query { courses { id title } }`;
function CourseList() {
const { loading, error, data } = useQuery(GET_COURSES);
if (loading) return <p>Loading…</p>;
if (error) return <p>Error: {error.message}</p>;
return data.courses.map((c) => <p key={c.id}>{c.title}</p>);
}
Other topics: persisted queries, caching (normalised cache by id + __typename), schema-first vs code-first (Nexus, Pothos, TypeGraphQL), federation (combining many GraphQL services), and code generation for TypeScript types (GraphQL Code Generator).
11. Examples with Output
Example 1 — Total lesson time per course (client-side shape)
query {
courses(level: ADVANCED) {
title
lessons {
minutes
}
}
}
{
"data": {
"courses": [
{
"title": "DSA in C++",
"lessons": [{ "minutes": 45 }, { "minutes": 70 }, { "minutes": 90 }]
},
{ "title": "React Projects", "lessons": [] }
]
}
}
Example 2 — __typename for client caches
query {
course(id: "c3") {
__typename
id
teacher {
__typename
name
}
}
}
{
"data": {
"course": {
"__typename": "Course",
"id": "c3",
"teacher": { "__typename": "Teacher", "name": "Hitesh" }
}
}
}
Example 3 — Same field twice with different arguments
query {
dsa: course(id: "c1") { title }
js: course(id: "c2") { title }
}
{
"data": {
"dsa": { "title": "DSA in C++" },
"js": { "title": "JavaScript Basics" }
}
}
12. Practice Problems
- Run the sample Apollo server and query all courses with their teacher names.
- Add a
rating: Floatfield toCoursewith a resolver that returns an average from reviews. - Add a
deleteCourse(id: ID!): Boolean!mutation. - Add a
search(text: String!): [Course!]!query that matches titles case-insensitively. - Implement cursor pagination (
coursesPage(first, after)). - Add authentication: only users with a teacher role may call
addCourse. - Fix an N+1 problem with DataLoader and log the number of database calls.
- Build a React page that lists courses with Apollo Client and adds a course with a mutation.
13. Interview Questions
1. GraphQL vs REST? REST has many endpoints with fixed responses; GraphQL has one endpoint and a typed schema where clients choose fields — avoiding over/under-fetching and multiple round trips.
2. What is a resolver?
A function that returns the value for a field. It receives (parent, args, context, info).
3. Query vs mutation vs subscription? Queries read data, mutations change data (executed in order), subscriptions stream real-time updates.
4. What is the N+1 problem and how do you solve it? Resolving a field per item causes one query per item. Batch and cache with DataLoader (one query per field type per request).
5. What does ! mean in a type?
Non-null — the field (or list item) is guaranteed never to be null.
6. What are fragments?
Reusable sets of fields (fragment X on Type { ... }) spread into queries with ...X.
7. How are errors returned?
In an errors array alongside data (which can be partial), usually with HTTP 200; resolvers throw GraphQLError with extension codes.
8. What is introspection?
Querying the schema itself (__schema, __type) — powers documentation, autocomplete and code generation. Often disabled in production.
9. How do you secure a GraphQL API? Authentication in context, authorization in resolvers, depth/complexity limits, rate limiting, disabling introspection in production, and persisted queries.
10. How is caching different from REST?
No URL-based HTTP caching by default (POST requests), so clients use normalised caches keyed by __typename + id, and servers use persisted queries or response caching.
14. Cheat Sheet & References
Schema (SDL)
# types, inputs, enums, operations
type User { id: ID! name: String! posts(limit: Int = 10): [Post!]! }
input NewUser { name: String! email: String! }
enum Role { ADMIN USER }
type Query { user(id: ID!): User users: [User!]! }
type Mutation { createUser(input: NewUser!): User! }
type Subscription { userCreated: User! }
Queries
query { users { id name } }
query GetUser($id: ID!) { user(id: $id) { name posts(limit: 3) { title } } }
query { me: user(id: "1") { name } other: user(id: "2") { name } }
fragment Basic on User { id name }
query { users { ...Basic } }
query ($full: Boolean!) { users { name email @include(if: $full) } }
Mutations and introspection
mutation ($input: NewUser!) { createUser(input: $input) { id } }
query { __schema { types { name } } }
query { __type(name: "User") { fields { name } } }
Server (Apollo)
const server = new ApolloServer({ typeDefs, resolvers });
const resolvers = { Query: { user: (parent, args, ctx) => ctx.db.users.get(args.id) } };
throw new GraphQLError("Not found", { extensions: { code: "NOT_FOUND" } });
const loader = new DataLoader((ids) => batchLoad(ids));
Official documentation