This prompt is designed for API developers and backend engineers who need to standardize the response shape of list endpoints. The primary job-to-be-done is transforming a raw, unstructured list of items from a model or an upstream service into a predictable, application-ready collection envelope. The ideal user is someone integrating AI-generated or AI-processed data into an existing API contract, where downstream clients expect consistent items arrays, total_count fields, and HATEOAS-style links for pagination. You should use this prompt when the core logic of item generation or retrieval is handled, but the final structural wrapping must be guaranteed before the response is serialized and sent over the wire.
Prompt
Collection Response Shaping Prompt for List Endpoints

When to Use This Prompt
Define the job, reader, and constraints for the Collection Response Shaping Prompt.
This prompt is not a replacement for your database query or your application's actual pagination logic. Do not use it to calculate real total_count values from a live database or to enforce business-logic-level authorization on individual items. Its strength is in shaping a given set of items into a consistent contract. The required context includes the raw items payload, the desired pagination metadata (offset, limit, total), and the base URL for link generation. The prompt is most effective when the upstream item schema is already well-defined; it will enforce that schema on every item in the collection, making it a powerful guardrail against partial or malformed objects leaking into the array. If your primary challenge is generating the items themselves or performing complex aggregation, use a dedicated generation or analysis prompt first, and pipe the result into this shaping prompt as a final assembly step.
Before implementing, identify the failure modes that matter most for your API consumers. If an empty collection should return a 200 OK with an empty items array rather than a 404, this prompt must be explicitly instructed to do so. If a single-item collection must still be wrapped in an array, validate that the output never accidentally flattens the structure. The next step is to copy the prompt template, replace the bracketed placeholders with your specific schema and endpoint details, and run it against a set of test cases that include empty sets, single items, and full pages. Pair this prompt with a JSON Schema validator in your API gateway or middleware to catch structural regressions before they reach a client.
Use Case Fit
Where the Collection Response Shaping Prompt works well, where it breaks, and what you must provide before using it in production.
Good Fit: Standardized List Endpoints
Use when: you are building or refactoring REST or REST-like list endpoints that need consistent pagination metadata, item arrays, and HATEOAS-style links. The prompt excels at wrapping a homogeneous array of items into a predictable envelope. Guardrail: Provide an explicit item schema so the model enforces field consistency across all objects in the collection.
Bad Fit: Heterogeneous or Union-Type Responses
Avoid when: your endpoint returns mixed item types, polymorphic objects, or union payloads where each array element has a different shape. The prompt assumes a single item schema. Guardrail: For mixed-type collections, use a Batch Operation Response Envelope instead, or split into separate endpoints per resource type.
Required Input: Item Schema and Collection Metadata
Risk: Without a defined item schema, the model may hallucinate fields, omit required properties, or produce inconsistent objects. Guardrail: Always supply a JSON Schema or TypeScript interface for the item shape, plus total_count, current offset or cursor, and base URL for link generation. Validate output against the schema before returning to clients.
Operational Risk: Empty and Single-Item Collections
Risk: Edge cases like empty result sets or single-item collections can produce malformed links, incorrect total_count, or missing pagination metadata. Guardrail: Include explicit instructions for empty collection handling (empty items array, total_count=0, no next/prev links) and test these cases in your eval suite before deployment.
Operational Risk: Link URL Drift
Risk: The model may generate incorrect or relative URLs for self/next/prev links, especially when base URL or query parameters are complex. Guardrail: Provide the exact base URL and query parameter template. Validate all generated links with a URL parser and reject responses with malformed or mismatched hostnames.
Variant: Cursor vs. Offset Pagination
Risk: Mixing cursor and offset pagination semantics in the same prompt produces confusing envelopes with contradictory metadata. Guardrail: Choose one pagination strategy per prompt instance. Use the Cursor-Based Pagination Envelope variant for large datasets; use this offset-based prompt for traditional page-numbered APIs. Never combine both in a single prompt.
Copy-Ready Prompt Template
A reusable prompt template with square-bracket placeholders for generating standardized collection response envelopes from list endpoint data.
This prompt template is designed to be copied directly into your prompt management system, IDE, or orchestration layer. It takes raw list data and context about the API's pagination strategy and produces a structured collection envelope with items, metadata, and navigation links. The template uses square-bracket placeholders that you must replace with actual values before sending the prompt to a model. Each placeholder represents a variable input that changes per request—such as the items array, pagination parameters, or output schema constraints.
textYou are an API response formatter. Your task is to wrap a collection of items into a standardized list endpoint response envelope. ## Input Data - Items array: [ITEMS] - Pagination strategy: [PAGINATION_STRATEGY] - Current offset/page: [CURRENT_PAGE] - Page size/limit: [PAGE_SIZE] - Total item count: [TOTAL_COUNT] - Base URL for link generation: [BASE_URL] - Current request path: [REQUEST_PATH] ## Output Schema Produce a JSON object matching this structure: { "data": { "items": [ITEM_SCHEMA], "total_count": integer, "page": integer | null, "page_size": integer | null, "offset": integer | null, "limit": integer | null }, "links": { "self": string, "next": string | null, "prev": string | null, "first": string | null, "last": string | null }, "meta": { "request_id": string | null, "timestamp": string (ISO 8601), "collection_size": integer } } ## Constraints - Every item in the `items` array must conform to [ITEM_SCHEMA]. If an item is missing a required field, omit it and include a warning in `meta.warnings`. - For empty collections, `items` must be an empty array `[]`, not null or missing. - `total_count` must equal the length of the full unfiltered collection, not just the current page. - Generate `links` based on [PAGINATION_STRATEGY]: - If offset-based: use `offset` and `limit` query parameters. - If cursor-based: use `cursor` query parameter with opaque cursor values derived from item IDs. - If page-based: use `page` and `per_page` query parameters. - Set `next` to null when on the last page or when `total_count` indicates no more items. - Set `prev` to null when on the first page. - `meta.timestamp` must be the current time in ISO 8601 format. - Do not include any fields outside the specified schema. - Do not wrap the response in an explanatory message. Return only the JSON object. ## Examples Input: 3 items, offset=0, limit=10, total_count=3 Expected: items array with 3 items, next=null, prev=null, total_count=3 Input: 0 items, offset=0, limit=10, total_count=0 Expected: items=[], next=null, prev=null, total_count=0 Input: 5 items, offset=10, limit=5, total_count=27 Expected: items array with 5 items, next link present, prev link present, total_count=27 ## Risk Level [RISK_LEVEL] ## Additional Context [CONTEXT]
To adapt this template for your application, replace each square-bracket placeholder with concrete values at runtime. [ITEMS] should contain the serialized array of records for the current page. [ITEM_SCHEMA] should describe the expected shape of each item—either as a JSON Schema fragment or a natural language description of required fields and types. [PAGINATION_STRATEGY] must be one of offset, cursor, or page to control link generation logic. [RISK_LEVEL] should be set to low, medium, or high to adjust the model's caution; for high-risk contexts such as financial or healthcare data, add explicit instructions to refuse generation if item schemas are violated. [CONTEXT] can include additional business rules, such as maximum page size limits or tenant isolation requirements. After substitution, validate the prompt by running it against known test cases—empty collections, single-item collections, and boundary pages—before deploying to production.
Prompt Variables
Required inputs for the Collection Response Shaping Prompt. Each placeholder must be populated before the prompt is sent to the model. Missing or malformed variables are the most common cause of envelope structure failures.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[ITEMS] | The array of data objects to wrap in the collection envelope. This is the primary payload. | [{"id": "usr_01", "name": "Alice"}, {"id": "usr_02", "name": "Bob"}] | Must be a valid JSON array. Empty array is allowed. Each element must be a JSON object. Validate with JSON.parse before insertion. |
[TOTAL_COUNT] | The total number of items available across all pages, not just the current page. Used for pagination metadata. | 47 | Must be a non-negative integer. Must be greater than or equal to the length of [ITEMS]. Parse as integer and check >= 0. |
[SELF_LINK] | The full URL for the current page of results. Used in the links object for HATEOAS compliance. | Must be a valid absolute URL. Validate with URL constructor or regex. Must include scheme and host. Query parameters must match current pagination state. | |
[NEXT_LINK] | The full URL for the next page of results. Set to null when there is no next page. | Must be a valid absolute URL or null. When null, the model must omit the next field or set it to null per the output schema. Validate null handling explicitly. | |
[PREV_LINK] | The full URL for the previous page of results. Set to null when on the first page. | null | Must be a valid absolute URL or null. When offset is 0, this must be null. Validate that prev is null when offset equals 0. |
[ITEM_SCHEMA_DESCRIPTION] | A natural language description of the required shape for each item in the items array. Guides the model to enforce consistency. | Each item must have: id (string, required), name (string, required), email (string, optional), created_at (ISO 8601 string, required) | Must be a non-empty string. Should describe field names, types, and required/optional status. Schema description is used for output validation, not just generation. |
[COLLECTION_NAME] | The semantic name of the collection, used in metadata and for human-readable error messages. | users | Must be a non-empty, lowercase, alphanumeric string with underscores allowed. Used to generate the data wrapper key. Validate against /^[a-z][a-z0-9_]*$/. |
[PAGINATION_STYLE] | Specifies the pagination method: offset, cursor, or page. Determines which metadata fields are included. | offset | Must be one of: offset, cursor, page. Enum validation required. Mismatch between style and provided links will cause broken pagination. |
Implementation Harness Notes
How to wire the Collection Response Shaping Prompt into a production API gateway, validation layer, and retry loop.
The Collection Response Shaping Prompt is designed to sit behind an API endpoint that aggregates data from a model and returns it in a predictable envelope. The prompt itself is stateless; the application layer must supply the raw items, pagination metadata, and any link generation logic. The model's job is strictly to assemble these inputs into the target envelope structure, enforce item schema consistency, and handle edge cases like empty collections or single-item lists. Do not rely on the model to calculate total_count or generate accurate next/prev links from scratch—these values should be computed by your application and passed into the prompt as [CONTEXT] variables.
Wire the prompt into a service function that accepts a list of items, a pagination state object, and a base URL for link construction. Before calling the model, validate that all items conform to the expected item schema at the application level. The model should receive pre-validated items and focus on envelope assembly, not data cleaning. After receiving the model's JSON response, run a strict post-generation validator that checks: (1) the root object contains items, total_count, and links keys; (2) items is an array and every element matches the item schema; (3) total_count is a non-negative integer matching the application's known count; (4) links.self, links.next, and links.prev are either valid URLs or null; and (5) empty collections produce items: [] with links.next and links.prev set to null. If validation fails, retry once with the validation error message appended to the prompt as a correction hint. If the retry also fails, log the failure, return a 500 error with a fallback envelope, and alert the on-call channel.
For model selection, prefer models with strong JSON mode and schema-following behavior (e.g., GPT-4o with structured outputs, Claude 3.5 Sonnet with tool use set to a no-op function returning the envelope schema). Avoid models that struggle with consistent link generation or that hallucinate pagination values. In high-throughput scenarios, consider caching the system prompt prefix and batching multiple collection requests into a single model call where each request is a separate envelope assembly task. Implement request ID and trace ID propagation through the prompt context so that every generated envelope can be correlated back to the originating API request in your observability platform. Finally, add an eval suite with golden test cases covering: empty collection, single item, full page, last page (where next is null), and malformed input items. Run these evals on every prompt change before deployment.
Expected Output Contract
Defines the exact shape, types, and validation rules for the collection response envelope. Use this contract to build a post-generation validator or schema check before the response reaches the API gateway.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
items | Array of Objects | Must be an array. Empty array is valid. Each element must match the [ITEM_SCHEMA] exactly. | |
total_count | Integer | Must be a non-negative integer. Must equal the total number of items matching the query, not just the length of the items array when paginated. | |
_links.self.href | String (URI) | Must be a valid, absolute URI. Must return the current collection when called without modification. | |
_links.next.href | String (URI) or null | If present, must be a valid absolute URI. Must be null when the current page is the last page. Must not be present alongside an empty items array. | |
_links.prev.href | String (URI) or null | If present, must be a valid absolute URI. Must be null when the current page is the first page. Must not be present when offset is 0. | |
error | Object or null | If present, must conform to the [ERROR_SCHEMA]. Must be null on successful responses. Presence requires a non-2xx HTTP status code. | |
items[].id | String | Must be a non-empty string. Must be unique within the items array for a single response. | |
items[].updated_at | String (ISO 8601) | Must be a valid ISO 8601 datetime string. Must not be in the future relative to the server's clock. |
Common Failure Modes
Collection response shaping fails in predictable ways. These are the most common production failure modes and how to prevent them before they reach an API consumer.
Schema Drift Across Collection Items
Risk: The model produces items with inconsistent field presence—some objects include optional fields while others omit them, or field types change between array elements. Downstream clients that expect homogeneous arrays break on the first mismatched record. Guardrail: Provide an explicit per-item JSON Schema in the prompt and add a post-generation validation step that checks every item against that schema. Reject the entire collection if any item fails, and retry with a stricter instruction that includes a counterexample of the drift.
Empty Collection Metadata Mismatch
Risk: When the items array is empty, the model generates inconsistent metadata—total_count shows 0 but next link is still populated, or page_count is 1 instead of 0. Clients relying on metadata for pagination logic enter infinite loops or display broken UI states. Guardrail: Add an explicit empty-collection example in the prompt showing total_count: 0, items: [], and null next/prev links. Validate that empty collections always have has_more: false and no navigation URLs before returning.
Link URL Hallucination
Risk: The model invents plausible but non-functional next, prev, or self URLs that don't match the actual API route structure. Clients follow these links and receive 404 errors, breaking automated pagination. Guardrail: Provide the exact base URL and query parameter convention in the prompt. Post-process all link fields with a regex check against the expected URL pattern. If links don't match, strip them and log a warning rather than returning broken URLs.
Total Count vs. Items Length Inconsistency
Risk: The model returns total_count: 25 but only 10 items in the array, or total_count: 0 with items present. This breaks client-side pagination math and causes data display errors. Guardrail: Add a deterministic post-processing rule: total_count must equal the length of the items array for unpaginated responses, or be greater than or equal to items.length for paginated responses. If the invariant fails, recalculate total_count from the actual array length and flag the response for review.
Single-Item Array Serialization
Risk: Some models collapse a single-item collection into a plain object instead of an array with one element, producing items: { ... } instead of items: [{ ... }]. JSON parsers that expect arrays throw type errors. Guardrail: Include a single-item example in the prompt that explicitly shows the array wrapper. Add a post-generation type check: if items is not an array, wrap it in an array and increment a counter metric. Never ship a collection response without verifying items is an array type.
Pagination Boundary Off-by-One Errors
Risk: The model miscalculates has_more or next_cursor at collection boundaries—returning has_more: true when the last page is reached, or omitting the final record. Clients either miss data or make unnecessary extra requests. Guardrail: Provide explicit boundary examples in the prompt: the last page with exactly page_size items, a page with fewer than page_size items, and an empty page. Validate that has_more is false when items.length < page_size, and that next_cursor is null on the final page.
Evaluation Rubric
Test output quality before shipping the collection response shaping prompt. Each criterion targets a structural guarantee, edge case, or contract violation that breaks downstream API consumers.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Envelope structure completeness | Response contains items, total_count, and links at root level | Missing required key; items is not an array; total_count is not an integer | Schema validation against expected JSON Schema; parse check on response body |
Empty collection handling | items is empty array [], total_count is 0, links.self present, links.next is null | items is null or missing; total_count is negative; next link contains cursor or offset | Send input that yields zero results; assert array emptiness and null next link |
Single-item collection handling | items array length is 1, total_count is 1, links.next is null, links.prev is null | Single item wrapped in object instead of array; prev link populated incorrectly | Send input that yields exactly one result; assert array length and null navigation links |
Item schema consistency across collection | Every item in items array has identical keys and types; no field present in one item and missing in another | Field drift: first item has description but third item omits it; type mismatch on same field name | Extract all item keys; assert set equality across all items; type-check each field positionally |
Pagination link correctness | links.self matches request parameters; links.next increments offset or advances cursor; links.prev decrements or is null on first page | Self link omits query params; next link points to same page; prev link present on page 1 | Parse link URLs; assert query parameter values match expected offset/cursor transitions |
total_count accuracy | total_count matches actual number of items that would be returned without pagination | total_count equals items.length when more items exist; total_count changes between pages | Count all items across full unpaginated result set; assert total_count equals that count on every page |
Boundary offset handling | Requesting offset beyond total_count returns items [], total_count unchanged, links.prev present, links.next null | Returns 400-style error instead of empty envelope; total_count resets to 0; prev link missing | Send offset greater than total_count; assert empty items array and preserved total_count |
Malformed input resilience | Invalid or missing pagination parameters produce a validation error envelope, not a broken collection | Prompt hallucinates items for invalid input; returns 200 with partial data; crashes on missing offset | Send request with offset=-1 or limit=0; assert error envelope with problem details structure |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt
Use the base prompt with a simplified schema. Drop prev and next link generation initially. Accept total_count as optional. Focus on getting the items array shape right first.
code[SYSTEM]: You are an API response formatter. Given [INPUT_DATA] and [ITEM_SCHEMA], return a JSON collection envelope with an "items" array and optional "total_count".
Watch for
- Items that don't match the provided schema
- Missing
itemskey when collection is empty - Inconsistent field casing across items

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.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us