Inferensys

Prompt

GraphQL Response Shaping Prompt Template

A practical prompt playbook for using GraphQL Response Shaping Prompt Template in production AI workflows.
Operations team reviewing AI workflow automation on laptop, workflow builder visible, casual office setup.
PROMPT PLAYBOOK

When to Use This Prompt

Define the job, the ideal user, and the operational boundaries for the GraphQL Response Shaping prompt.

This prompt is designed for GraphQL gateway and backend-for-frontend (BFF) teams who need to transform raw service data into a JSON payload that strictly conforms to a requested GraphQL query shape. The core job-to-be-done is field-level response shaping: given a raw data object and a GraphQL query string, the model must return a JSON response containing only the fields requested in the query, respecting nested selections, aliases, and field renames. The ideal user is an engineering lead or backend developer building a product feature where a lightweight, AI-driven shaping layer sits between upstream services and a GraphQL response, often as a fallback or augmentation to a traditional resolver.

Use this prompt when you control the raw data input and need a flexible, schema-aware transformation that would be tedious to hard-code for rapidly changing queries. It is appropriate for prototyping GraphQL facades, normalizing responses from third-party APIs that don't natively support GraphQL, or building internal tools where strict resolver logic is overkill. Do not use this prompt when you need guaranteed, bit-exact response shaping at high throughput; a compiled resolver or a deterministic JSON transformation library is the correct tool for that. This prompt is also unsuitable for queries with deeply nested fragments, complex @skip/@include directives, or field-level authorization logic, as the model's probabilistic nature introduces risk of field leakage or omission.

Before using this prompt, you must have the raw data payload and the exact GraphQL query string available at runtime. The prompt assumes the raw data is a superset of the requested fields; it does not fetch missing data. The primary failure mode is field inclusion error, where the model either includes unrequested fields (over-fetching) or omits requested fields (under-fetching). A secondary risk is alias mishandling, where a field requested with an alias is returned under its original name. To mitigate these risks, you must pair this prompt with a post-generation validation step that parses the GraphQL query, extracts the expected response shape, and diffs it against the model's output. For any production use case involving user data, implement a human review or automated approval gate before the shaped response is returned to the client.

PRACTICAL GUARDRAILS

Use Case Fit

Where the GraphQL Response Shaping Prompt Template works well and where it introduces risk. Use these cards to decide if this prompt is the right tool before wiring it into your gateway.

01

Good Fit: GraphQL Gateway Response Shaping

Use when: You are building a GraphQL gateway that must return JSON payloads matching the exact field selection of an incoming query. Guardrail: Validate the output against the original query shape before returning it to the client. Reject responses that include unrequested fields or omit non-nullable selections.

02

Good Fit: Field-Level Inclusion Accuracy

Use when: Your primary requirement is strict field inclusion—returning only what was requested, including nested selections and aliased fields. Guardrail: Implement a post-generation diff that compares the output keys against the parsed query selection set. Flag any mismatch for repair or rejection.

03

Bad Fit: Full GraphQL Query Execution

Avoid when: You need a complete GraphQL execution engine that resolves arguments, variables, fragments, directives, and complex resolver logic. Guardrail: This prompt shapes responses; it does not replace a GraphQL server. Use it only for the response formatting layer, not for query parsing or execution.

04

Bad Fit: Real-Time Streaming Subscriptions

Avoid when: You are building GraphQL subscription endpoints that require incremental delivery and event-driven updates. Guardrail: This prompt is designed for single-turn request-response shaping. For subscriptions, use a dedicated pub/sub infrastructure and apply schema validation separately.

05

Required Inputs: Parsed Query Shape

Risk: The model cannot reliably parse raw GraphQL query strings to determine the selection set. Guardrail: Pre-process the query server-side to extract the requested field tree, aliases, and nested selections. Pass the parsed shape as structured input to the prompt, not the raw query string.

06

Operational Risk: Alias and Fragment Mismatch

Risk: Aliased fields and named fragments can cause the model to return data under the wrong key or duplicate content across selections. Guardrail: Include explicit alias-to-field mappings in the prompt input. Test with queries that use multiple aliases on the same field and verify key correctness in the output.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template with square-bracket placeholders for shaping GraphQL responses that match requested field selections.

This template is designed to be copied directly into your prompt management system, API call, or evaluation harness. It instructs the model to generate a JSON payload that conforms precisely to a provided GraphQL query shape, including only the fields requested, respecting aliases, and handling nested selections. The square-bracket placeholders represent the dynamic inputs your application must supply at runtime. Do not leave them unresolved in production.

text
You are a GraphQL response shaping engine. Your task is to generate a JSON response body that exactly matches the field selection in the provided GraphQL query.

[INPUT]

[GRAPHQL_QUERY]

[OUTPUT_SCHEMA]

[CONSTRAINTS]
- Include ONLY the fields explicitly requested in the GraphQL query. Do not add extra fields.
- If a field has an alias in the query, use the alias as the key in the JSON response.
- For nested object selections, produce nested JSON objects containing only the requested sub-fields.
- If the query includes fragments, resolve them inline and apply the same field inclusion rules.
- If a requested field is not available in [INPUT], omit the key entirely unless [NULL_HANDLING] specifies otherwise.
- Do not include __typename unless explicitly requested in the query.
- Output ONLY the valid JSON object. No markdown fences, no explanatory text.

[NULL_HANDLING]

[EXAMPLES]

Query:
query { user { id name email } }

Input Data:
{ "user": { "id": 1, "name": "Alice", "email": "alice@example.com", "role": "admin" } }

Output:
{ "user": { "id": 1, "name": "Alice", "email": "alice@example.com" } }

Query with alias:
query { customer: user { id fullName: name } }

Input Data:
{ "user": { "id": 1, "name": "Alice", "email": "alice@example.com" } }

Output:
{ "customer": { "id": 1, "fullName": "Alice" } }

Now generate the response for [GRAPHQL_QUERY] using [INPUT].

To adapt this template, replace each placeholder with the actual data your application manages. [INPUT] should contain the full data object from your resolver or data source. [GRAPHQL_QUERY] is the raw query string. [OUTPUT_SCHEMA] can optionally contain a JSON Schema for post-generation validation. [NULL_HANDLING] should specify whether null fields are included (e.g., "field": null) or omitted entirely. The [EXAMPLES] block provides few-shot demonstrations; extend it with edge cases from your own schema, such as array fields, inline fragments, or union types. After generating the response, always validate it against the expected shape using a JSON Schema validator or a field-inclusion checker before returning it to the client.

IMPLEMENTATION TABLE

Prompt Variables

Placeholders required by the GraphQL Response Shaping Prompt Template. Substitute these before inference to produce a payload that matches the requested field selections.

PlaceholderPurposeExampleValidation Notes

[GRAPHQL_QUERY]

The raw GraphQL query string defining the requested fields, aliases, and nested selections.

query { user(id: 1) { name email } }

Parse check: must be a valid GraphQL query string. Reject if empty or contains mutation operations.

[DATA_SOURCE_JSON]

The raw backend response payload (e.g., REST or database JSON) containing all available fields for the queried entity.

{"user": {"id": 1, "name": "Ada", "email": "ada@example.com", "role": "admin"}}

Schema check: must be valid JSON. Null allowed if no data exists. Validate that top-level entity key matches the query root field.

[OUTPUT_SCHEMA]

A JSON Schema definition that the final shaped response must validate against.

{"type": "object", "properties": {"user": {"type": "object", "properties": {"name": {"type": "string"}, "email": {"type": "string"}}}}, "required": ["user"]}

Schema check: must be valid JSON Schema. Validate that required fields match the requested selections in [GRAPHQL_QUERY].

[FIELD_SELECTION_RULES]

Natural-language or structured rules for field inclusion, such as 'Include only fields explicitly requested in the query. Exclude all others.'

Include only fields present in the GraphQL query selection set. Omit fields not requested, even if present in the data source.

Parse check: must be a non-empty string. Confirm rules are unambiguous about inclusion/exclusion behavior.

[ALIAS_HANDLING_RULES]

Instructions for how to handle field aliases in the query, mapping alias names to original field names in the output.

If a field has an alias (e.g., 'fullName: name'), use the alias as the key in the output JSON. Do not include the original field name.

Parse check: must be a non-empty string. Test with a query containing aliases to confirm alias keys appear and original keys do not.

[NESTED_SELECTION_RULES]

Rules for handling nested object selections, including how deep to traverse and whether to include parent objects.

For nested selections (e.g., 'address { city }'), include the parent object with only the requested child fields. Do not flatten the structure.

Parse check: must be a non-empty string. Validate with a query containing nested fields to confirm structure preservation.

[NULL_HANDLING_POLICY]

Specification for how to handle null or missing fields in the data source when they are requested in the query.

If a requested field is null or absent in the data source, include the field with a null value in the output. Do not omit the field.

Parse check: must be a non-empty string. Test with a data source containing null fields to confirm null values are present in output.

[MAX_DEPTH_LIMIT]

The maximum nesting depth allowed for the response payload, preventing infinite recursion.

5

Type check: must be a positive integer. Validate that output does not exceed this depth. Reject queries requesting deeper nesting.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the GraphQL Response Shaping prompt into a production gateway or API workflow.

This prompt is designed to sit inside a GraphQL gateway or a backend-for-frontend (BFF) layer where the model receives a user's natural-language request and the parsed GraphQL query shape, then returns a JSON payload that matches the requested field selections exactly. The implementation harness must ensure that the model never sees the raw user input without the accompanying query shape, and that the output is validated against the expected selection set before it reaches the client.

Wire the prompt into a request pipeline with three stages: pre-processing, inference, and post-validation. In pre-processing, parse the incoming GraphQL query to extract the requested field names, nested selections, and any aliases. Inject these into the [QUERY_SHAPE] placeholder as a structured description—do not pass the raw GraphQL SDL string unless the model has been explicitly fine-tuned to interpret it. For inference, use a model with strong JSON-mode or structured-output support (e.g., GPT-4o with response_format: { type: 'json_object' } or Claude with a prefill { token). Set temperature to 0 or near-zero to reduce field hallucination. Log the full assembled prompt, the raw model response, and the parsed JSON payload for every request. If the model returns malformed JSON, retry once with a repair prompt that includes the parse error message and the original [QUERY_SHAPE]; if the second attempt fails, fall back to a static error response and alert the operations channel.

Post-validation is the critical safety net. Before returning the payload to the client, validate that every key in the model's output exists in the requested selection set and that no extra fields have been introduced. For nested selections, recurse through the output object and the query shape in parallel. If the query uses aliases, confirm the output keys match the alias names, not the underlying field names. Run an eval check that measures field precision (no extra fields), field recall (all requested fields present for non-null data), and alias fidelity (alias keys match exactly). For high-risk domains where incorrect field exposure could leak data, route outputs that fail validation to a human review queue before any client response is sent. This harness turns the prompt from a one-shot generation into a reliable, auditable component of your API surface.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the required fields, types, and validation rules for the GraphQL-shaped JSON response. Use this contract to build post-generation validators and eval checks.

Field or ElementType or FormatRequiredValidation Rule

data

object

Top-level key must be 'data'. Reject if missing or if response is a flat array.

data.<fieldName>

object | array | scalar

Field name must exactly match a root field requested in [GRAPHQL_QUERY]. No extra fields allowed.

data.<fieldName>.<nestedField>

object | array | scalar

Nested field must exist in the query selection set. Reject if field is not requested in [GRAPHQL_QUERY].

errors

array of objects

If present, each item must have a 'message' string. 'locations' and 'path' are optional. Reject if 'errors' is not an array.

errors[].message

string

Must be a non-empty string describing the error. Reject if null or missing.

data.<fieldName> (alias)

object | array | scalar

If [GRAPHQL_QUERY] uses an alias, the response key must be the alias, not the original field name. Reject on mismatch.

data.__typename

string

If present, must match the expected type name from the schema. Reject if type name is invalid for the requested object.

extensions

object

If present, must be a flat object. Reject if it contains nested 'data' or 'errors' keys that conflict with the top-level contract.

PRACTICAL GUARDRAILS

Common Failure Modes

When shaping GraphQL responses with an LLM, these are the most common failure patterns and how to prevent them before they reach production.

01

Phantom Field Inclusion

What to watch: The model includes fields that were not requested in the GraphQL query, especially nested fields it 'thinks' are helpful. This breaks the contract that the response shape matches the request shape exactly. Guardrail: Post-process the generated JSON against the parsed query selection set. Strip any field not present in the requested shape before returning the response to the client.

02

Missing Nested Selections

What to watch: The model returns a scalar or null for a field that requires nested object selection (e.g., returning "author": "Jane" instead of "author": { "name": "Jane" }). This happens when the prompt underspecifies the depth of the requested shape. Guardrail: Include the full parsed selection set with depth markers in the prompt. Validate that every object-type field in the response is an object, not a scalar.

03

Alias Drift

What to watch: When the query uses aliases (e.g., admin: user(role: ADMIN)), the model reverts to the original field name in the response instead of the alias key. This breaks client-side data access patterns. Guardrail: Explicitly map each alias to its response key in the prompt instructions. Add a validation step that checks response keys against the query's alias map and corrects mismatches.

04

Fragment Spread Collapse

What to watch: The model fails to merge fields from multiple fragment spreads on the same type, returning only the fields from the last fragment or duplicating the object. This is common with inline fragments on interfaces or unions. Guardrail: Pre-resolve fragment spreads into a flat field list before constructing the prompt. Provide the model with the fully merged selection set per type rather than raw fragment syntax.

05

Null vs. Absent Field Confusion

What to watch: The model omits a requested field entirely when the value is null, instead of including the key with a null value. In GraphQL, "field": null and absent are semantically different and affect client-side caching and nullability contracts. Guardrail: Add an explicit instruction: 'Every requested field must appear in the response object. Use null for missing or unknown values. Do not omit keys.' Validate key presence against the selection set.

06

List vs. Single Object Type Error

What to watch: The model returns a single object when the schema defines a list type, or wraps a single object in an array when the schema expects a scalar. This is especially common when the underlying data has one or zero results. Guardrail: Include the expected type cardinality from the schema in the field descriptions within the prompt. Add a type-check validator that confirms arrays are arrays and scalars are scalars before returning the response.

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for testing whether the GraphQL response shaping prompt produces correct, production-ready outputs before shipping. Each row defines a pass standard, a failure signal, and a test method.

CriterionPass StandardFailure SignalTest Method

Field Inclusion Accuracy

Output contains only fields requested in the GraphQL selection set; no extra fields present

Extra fields appear in response that were not requested in the query

Diff output keys against parsed query selection set; flag any key not in the requested set

Nested Selection Matching

Nested object fields match the exact sub-selection requested; no missing or extra nested fields

Nested object omits a requested sub-field or includes an unrequested sub-field

Recursive walk of output against query AST; compare at each nesting level

Alias Handling

Fields requested with aliases appear under the alias key in output, not the original field name

Output uses original field name instead of the alias specified in the query

Parse query for alias definitions; verify output key matches alias, not field name

Required Field Presence

All non-null fields in the schema that are requested return a value or explicit null per schema contract

Missing key for a requested non-null field or absent field where schema requires presence

Validate output against GraphQL schema; check that all requested non-null fields have a key present

Type Conformance

Each output field value matches the GraphQL schema type: String, Int, Float, Boolean, ID, Enum, or List

Type mismatch such as string where int expected or array where scalar expected

Run type assertion per field against schema definition; flag type mismatches

Enum Value Validity

Enum fields contain only values defined in the schema's enum type definition

Enum field contains a value not listed in the schema enum or a misspelled variant

Extract enum definitions from schema; validate output enum values against allowed set

Null vs Absent Semantics

Fields requested but having null values appear with key present and value null; unrequested fields are absent

Null field key is missing entirely or an unrequested field appears with null

Check key presence for all requested fields; verify null fields have key present, unrequested fields have no key

List Field Cardinality

List fields return arrays; empty lists use [] not null or absent key when field is requested

List field returns null instead of empty array or returns scalar instead of array

Assert list fields are arrays; check empty list representation matches [] not null

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Start with the base template and a single representative query. Remove strict validation instructions and focus on getting the field-selection logic right. Use a small sample of 3-5 GraphQL queries with varying depth and aliases.

code
You are a GraphQL response shaper. Given a GraphQL query and the raw resolver data, return a JSON response containing ONLY the fields requested in the query selection set.

Query: [GRAPHQL_QUERY]
Raw data: [RAW_DATA]

Watch for

  • Missing nested field pruning when a parent is requested but children are not
  • Alias handling silently dropping renamed fields
  • Returning null for missing fields instead of omitting them entirely
Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.