π Declarative Data Fetching, Schema Introspection & Granular Graph Validation
Unlike REST architectural patterns where endpoints return rigid data shapes bound to specific HTTP verbs and resource URIs, GraphQL operates through a single multiplexed endpoint (typically POST /graphql). Clients declare the exact data requirements they need, eliminating over-fetching and under-fetching. However, this flexibility introduces unique automation challenges: GraphQL servers almost universally return HTTP 200 OK even when syntax, validation, or business logic failures occur, placing error telemetry inside a root-level errors array rather than HTTP transport status lines. In Postman, GraphQL is supported natively via specialized request body formatting, separated GraphQL JSON variable panes, schema introspection auto-completion, and Chai.js BDD assertions designed to traverse nested data nodes while strictly confirming the absence or structure of execution errors.
data and errors response envelope.
POSTMAN GRAPHQL CLIENT COMPILATION & WIRE PROTOCOL:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β POSTMAN GRAPHQL REQUEST BUILDER β
β Query Pane: GraphQL Variables Pane (JSON): β
β query GetCandidate($id: ID!) { { β
β candidate(id: $id) { name email credits } "id": "{{activeStudentId}}" β
β } } β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ (Compiled into single JSON string)
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β RAW HTTP POST WIRE PACKET: POST /graphql HTTP/1.1 β
β Content-Type: application/json β
β { β
β "query": "query GetCandidate($id: ID!) { candidate(id: $id) { name email credits } }", β
β "variables": { "id": "STU-88219" } β
β } β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β GRAPHQL SERVER EXECUTION (Schema Validation βββΊ Resolver Tree βββΊ Serializer) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
ββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββ
βΌ βΌ
ββββββββββββββββββββββββββββββββββββββββββββββββ ββββββββββββββββββββββββββββββββββββββββββββββββ
β SUCCESS ENVELOPE (HTTP 200 OK) β β PARTIAL / TOTAL ERROR (HTTP 200 OK!) β
ββββββββββββββββββββββββββββββββββββββββββββββββ€ ββββββββββββββββββββββββββββββββββββββββββββββββ€
β { β β { β
β "data": { β β "data": null, β
β "candidate": { β β "errors": [ β
β "name": "Nikita Sharma", β β { "message": "Cannot query field...", β
β "credits": 4 β β "locations": [{"line":2,"column":5}], β
β } β β "path": ["candidate", "credits"] } β
β } β β ] β
β } β β } β
β β’ "data" is fully populated β β β’ "errors" array indicates graph failures β
β β’ "errors" property is omitted entirely β β β’ Transport status remains 200 OK! β
ββββββββββββββββββββββββββββββββββββββββββββββββ ββββββββββββββββββββββββββββββββββββββββββββββββ
-- 1. REQUEST CONFIGURATION --
Method: POST
URL: {{baseUrl}}/graphql
Headers:
Content-Type: application/json
Body Mode: GraphQL
-- 2. GRAPHQL QUERY EDITOR PANE --
query FetchStudentCatalog {
students(limit: 5, status: ACTIVE) {
id
fullName
email
academicTrack
enrolledCredits
}
}
-- 3. TESTS TAB: VERIFYING GRAPHQL DATA CONTRACT --
// ==============================================================================
// STEP: POST /graphql (FetchStudentCatalog) - TESTS TAB
// ==============================================================================
pm.test("[TRANSPORT CONTRACT] Server responded with HTTP 200 OK", function () {
pm.response.to.have.status(200);
pm.response.to.have.header("Content-Type", /application\/json/);
});
pm.test("[GRAPHQL SUCCESS] Query executed with zero graph execution errors", function () {
const res = pm.response.json();
// Assert that the GraphQL errors array is completely absent
pm.expect(res).to.not.have.property("errors");
pm.expect(res).to.have.property("data");
pm.expect(res.data).to.be.an("object");
});
pm.test("[DATA INTEGRITY] Student list adheres to requested field projection", function () {
const students = pm.response.json().data.students;
pm.expect(students).to.be.an("array").that.is.not.empty;
pm.expect(students.length).to.be.at.most(5);
// Verify first candidate in graph array
const candidate = students[0];
pm.expect(candidate).to.have.all.keys("id", "fullName", "email", "academicTrack", "enrolledCredits");
pm.expect(candidate.id).to.match(/^STU-[0-9]{5,}$/);
pm.expect(candidate.enrolledCredits).to.be.a("number").and.above(0);
// Cache primary ID for downstream mutation testing
pm.environment.set("activeStudentId", candidate.id);
console.log(`[+] Captured Student ID from Graph: ${candidate.id}`);
});
-- 1. GRAPHQL QUERY EDITOR PANE --
query GetStudentById($candidateId: ID!, $includeGrades: Boolean!) {
student(id: $candidateId) {
id
fullName
academicTrack
enrolledCredits
grades @include(if: $includeGrades) {
courseCode
letterGrade
score
}
}
}
-- 2. GRAPHQL VARIABLES PANE (JSON FORMAT WITH POSTMAN VARIABLES) --
{
"candidateId": "{{activeStudentId}}",
"includeGrades": true
}
-- 3. PRE-REQUEST SCRIPT: ENSURING VARIABLE INITIALIZATION --
// ==============================================================================
// PRE-REQUEST SCRIPT: Guarantee Parameter Binding
// ==============================================================================
if (!pm.environment.get("activeStudentId")) {
pm.environment.set("activeStudentId", "STU-88219");
console.log("[*] Initialized activeStudentId fallback in environment.");
}
-- 4. TESTS TAB: VERIFYING CONDITIONAL DIRECTIVE RESOLUTION --
pm.test("[VARIABLE RESOLUTION] Query correctly resolved arguments and directives", function () {
pm.response.to.have.status(200);
const res = pm.response.json();
pm.expect(res).to.not.have.property("errors");
const student = res.data.student;
pm.expect(student.id).to.eql(pm.environment.get("activeStudentId"));
// Verify @include directive rendered the conditional grades field
pm.expect(student).to.have.property("grades");
pm.expect(student.grades).to.be.an("array");
console.log(`[β] Verified ${student.grades.length} grade entries for ${student.id}`);
});
enrollStudent mutation, passing a complex input object, and extracting the newly minted record ID.
-- 1. GRAPHQL MUTATION PANE --
mutation RegisterCandidate($input: RegisterCandidateInput!) {
registerCandidate(input: $input) {
recordId
status
enrolledAt
student {
fullName
email
academicTrack
}
}
}
-- 2. GRAPHQL VARIABLES PANE (JSON) --
{
"input": {
"fullName": "Nikita Sharma",
"email": "candidate.{{$timestamp}}@nikita-infotech.com",
"academicTrack": "ENTERPRISE_AUTOMATION",
"requestedCredits": 4
}
}
-- 3. TESTS TAB: MUTATION RESPONSE VERIFICATION --
// ==============================================================================
// STEP: POST /graphql (RegisterCandidate Mutation) - TESTS TAB
// ==============================================================================
pm.test("[MUTATION EXECUTION] Candidate registration mutation committed successfully", function () {
pm.response.to.have.status(200);
const res = pm.response.json();
pm.expect(res).to.not.have.property("errors");
const mutationResult = res.data.registerCandidate;
pm.expect(mutationResult).to.have.property("recordId");
pm.expect(mutationResult.status).to.eql("PROVISIONED");
pm.expect(mutationResult.student.academicTrack).to.eql("ENTERPRISE_AUTOMATION");
// Persist new record ID for downstream queries or mutations
pm.environment.set("registeredRecordId", mutationResult.recordId);
console.log(`[β] Mutation Success: Created Registration Record: ${mutationResult.recordId}`);
});
HTTP 200 OK alongside an errors array detailing violated field paths.
-- 1. GRAPHQL QUERY EDITOR PANE (REQUESTING UNAUTHORIZED BILLING LEDGER) --
query FetchRestrictedLedger($id: ID!) {
student(id: $id) {
id
fullName
# Restricted administrative field that standard user tokens cannot query:
restrictedFinancialLedger {
accountBalance
creditCardToken
}
}
}
-- 2. GRAPHQL VARIABLES PANE --
{
"id": "STU-88219"
}
-- 3. SERVER RESPONSE (HTTP 200 OK WITH GRAPHQL ERRORS ENVELOPE) --
// {
// "data": {
// "student": {
// "id": "STU-88219",
// "fullName": "Nikita Sharma",
// "restrictedFinancialLedger": null
// }
// },
// "errors": [
// {
// "message": "Unauthorized access to field 'restrictedFinancialLedger'",
// "locations": [{ "line": 5, "column": 5 }],
// "path": ["student", "restrictedFinancialLedger"],
// "extensions": { "code": "FORBIDDEN_FIELD_ACCESS" }
// }
// ]
// }
-- 4. TESTS TAB: ASSERTING GRAPH ERRORS & PATHS --
pm.test("[ERROR ENVELOPE] Server returned expected GraphQL errors array", function () {
// Notice: Transport status is 200 OK despite graph authorization failure!
pm.response.to.have.status(200);
const res = pm.response.json();
pm.expect(res).to.have.property("errors");
pm.expect(res.errors).to.be.an("array").that.is.not.empty;
const authError = res.errors[0];
pm.expect(authError.message).to.include("Unauthorized access");
pm.expect(authError.path).to.deep.equal(["student", "restrictedFinancialLedger"]);
// Verify machine-readable extension code
if (authError.extensions) {
pm.expect(authError.extensions.code).to.eql("FORBIDDEN_FIELD_ACCESS");
}
// Verify partial data: Public fields resolved, protected field remained null
pm.expect(res.data.student.id).to.eql("STU-88219");
pm.expect(res.data.student.restrictedFinancialLedger).to.be.null;
console.log(`[β] Verified partial graph error on path: ${authError.path.join(".")}`);
});
__schema introspection endpoint to confirm that required object types, fields, queries, and mutations exist in the backend schema definition.
-- 1. GRAPHQL INTROSPECTION QUERY PANE --
query IntrospectStudentSchema {
__schema {
queryType {
name
fields {
name
type { name kind }
}
}
mutationType {
name
fields {
name
}
}
types {
name
kind
}
}
}
-- 2. TESTS TAB: VALIDATING SCHEMA CONTRACT INTEGRITY --
// ==============================================================================
// STEP: POST /graphql (IntrospectStudentSchema) - TESTS TAB
// ==============================================================================
pm.test("[INTROSPECTION CONTRACT] Target GraphQL types exist in backend schema", function () {
pm.response.to.have.status(200);
const schema = pm.response.json().data.__schema;
pm.expect(schema).to.be.an("object");
// 1. Validate Query Root Fields
const queryFieldNames = schema.queryType.fields.map(f => f.name);
pm.expect(queryFieldNames).to.include.members(["student", "students", "courseCatalog"]);
// 2. Validate Mutation Root Fields
const mutationFieldNames = schema.mutationType.fields.map(f => f.name);
pm.expect(mutationFieldNames).to.include.members(["registerCandidate", "cancelEnrollment"]);
// 3. Validate Core Domain Entity Types
const typeNames = schema.types.map(t => t.name);
pm.expect(typeNames).to.include.members([
"Student",
"Course",
"RegisterCandidateInput",
"AcademicTrackEnum"
]);
console.log("[β] GraphQL Schema Introspection Audit: All domain types and resolvers verified.");
});
StudentSummaryFields) to ensure consistent data assertions across multiple operations without duplication.
-- 1. GRAPHQL QUERY PANE WITH NAMED FRAGMENT --
query GetStudentComparativeProfile($idA: ID!, $idB: ID!) {
candidateA: student(id: $idA) {
...StudentSummaryFields
}
candidateB: student(id: $idB) {
...StudentSummaryFields
}
}
fragment StudentSummaryFields on Student {
id
fullName
email
academicTrack
enrolledCredits
}
-- 2. GRAPHQL VARIABLES PANE --
{
"idA": "STU-88201",
"idB": "STU-88202"
}
-- 3. TESTS TAB: UNIFORM FRAGMENT CONTRACT VALIDATION --
pm.test("[FRAGMENT CONSISTENCY] Both aliased graph nodes conform to fragment contract", function () {
pm.response.to.have.status(200);
const res = pm.response.json().data;
const requiredFragmentKeys = ["id", "fullName", "email", "academicTrack", "enrolledCredits"];
// Validate Candidate A
pm.expect(res.candidateA).to.have.all.keys(requiredFragmentKeys);
pm.expect(res.candidateA.id).to.eql("STU-88201");
// Validate Candidate B
pm.expect(res.candidateB).to.have.all.keys(requiredFragmentKeys);
pm.expect(res.candidateB.id).to.eql("STU-88202");
console.log("[β] Fragment contract verified across candidateA and candidateB.");
});
pm.sendRequest(). Serializes queries and variables into JSON strings to provision prerequisite test data before the main request runs.
// ==============================================================================
// PRE-REQUEST SCRIPT: Programmatic GraphQL Data Seeding via pm.sendRequest
// ==============================================================================
const graphqlEndpoint = pm.environment.get("baseUrl") + "/graphql";
// Formulate raw GraphQL operation string
const seedMutation = `
mutation SeedCandidate($name: String!, $email: String!) {
registerCandidate(input: { fullName: $name, email: $email, academicTrack: ENTERPRISE_AUTOMATION, requestedCredits: 4 }) {
recordId
student { id }
}
}
`;
const seedVariables = {
name: "Automated Seed Candidate",
email: `seed.${Date.now()}@nikita-infotech.com`
};
// Assemble standard GraphQL JSON wire body
const graphqlPayload = {
query: seedMutation,
variables: seedVariables
};
console.log("[*] Dispatching pre-request GraphQL seeding mutation...");
pm.sendRequest({
url: graphqlEndpoint,
method: "POST",
header: {
"Content-Type": "application/json",
"Authorization": "Bearer " + pm.environment.get("activeBearerToken")
},
body: {
mode: "raw",
raw: JSON.stringify(graphqlPayload)
}
}, function (err, res) {
if (err || res.code !== 200) {
console.error("[-] GraphQL Seeding Failed:", err || res.text());
throw new Error("Failed to seed prerequisite GraphQL candidate!");
}
const resJson = res.json();
if (resJson.errors) {
console.error("[-] GraphQL Resolver Error:", resJson.errors);
throw new Error("Seeding mutation returned GraphQL errors!");
}
const seededId = resJson.data.registerCandidate.student.id;
pm.environment.set("prerequisiteStudentId", seededId);
console.log(`[+] Prerequisite GraphQL Student Seeded: ${seededId}`);
});
# 1. RUN GRAPHQL COLLECTION VIA NEWMAN:
newman run collections/GraphQL_Student_Masterclass.postman_collection.json \
-e environments/Staging.postman_environment.json \
--folder "01_GraphQL_Queries_and_Mutations" \
-r cli,htmlextra \
--reporter-htmlextra-export reports/graphql_execution_report.html \
--bail
# ==============================================================================
# NEWMAN TERMINAL EXECUTION SUMMARY:
# ==============================================================================
# 01_GraphQL_Queries_and_Mutations
#
# β 1. POST FetchStudentCatalog (Query)
# POST https://api.nikita-infotech.com/graphql [200 OK, 84ms, 1.4KB]
# β [TRANSPORT CONTRACT] Server responded with HTTP 200 OK
# β [GRAPHQL SUCCESS] Query executed with zero graph execution errors
# β [DATA INTEGRITY] Student list adheres to requested field projection
#
# β 2. POST RegisterCandidate (Mutation)
# POST https://api.nikita-infotech.com/graphql [200 OK, 142ms, 1.1KB]
# β [MUTATION EXECUTION] Candidate registration mutation committed successfully
#
# β 3. POST FetchRestrictedLedger (Negative Error Path)
# POST https://api.nikita-infotech.com/graphql [200 OK, 92ms, 614B]
# β [ERROR ENVELOPE] Server returned expected GraphQL errors array
GRAPHQL SPECIFICATION & ASSERTION DIRECTIVE MATRIX:
βββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ¬βββββββββββββββββββ¬ββββββββββββββββββββββββββββββββ
β OPERATION / ENVELOPE β SYNTAX / PATH EXAMPLE β HTTP STATUS CODE β PRIMARY OPERATIONAL PURPOSE β
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββΌββββββββββββββββββββββββββββββββ€
β Query β query GetUsers { users {id} }β 200 OK β Read-only idempotent query β
β Mutation β mutation AddUser($i: Input!) β 200 OK β State modification (create/updβ
β Variables Pane β {"id": "{{activeId}}"} β N/A (JSON Input) β Decouples data from query textβ
β data Envelope β res.data.<operationName> β 200 OK β Container for resolved fields β
β errors Array β res.errors[0].message β 200 OK (Warning!)β Graph execution / syntax errorβ
β errors.path β res.errors[0].path β 200 OK β Pinpoints failing graph field β
β errors.extensions.code β res.errors[0].extensions.codeβ 200 OK β Machine-readable error code β
β Introspection β query { __schema { types } } β 200 OK β Queries backend SDL contract β
β Fragment β fragment F on Type { fields }β N/A (Query block)β Reusable field projections β
β Directives (@include) β @include(if: $condition) β N/A (Directive) β Conditional field rendering β
βββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββ΄βββββββββββββββββββ΄ββββββββββββββββββββββββββββββββ€
β TOP 5 GRAPHQL TESTING BEST PRACTICES: β
β 1. Never assert on HTTP 200 alone: Always assert pm.expect(res).to.not.have.property("errors"). β
β 2. Use the Variables pane for dynamic inputs: Avoid string concatenation inside the query string. β
β 3. Assert on errors.path for negative tests: Verify exact field paths where resolver errors occur. β
β 4. Audit introspection endpoints in production: Verify __schema is disabled in prod for security. β
β 5. Validate partial data: In negative tests, assert resolved fields exist while forbidden fields are null.β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ