How-To Guide

How to Reduce Payload Size with Field Selection

Shrink API payloads with field selection: support sparse fieldsets and expansions, avoid over-fetching, and keep responses cacheable and typed.

On this page

  1. Introduction
  2. Expose fields and expansions explicitly
  3. Validate against an allowlist
  4. Push the selection into the query
  5. Keep the response typed and cacheable
  6. Test size and correctness
  7. Common pitfalls
  8. Conclusion

Introduction

An API that returns every field of every object is easy to write and wasteful to use. A mobile client on a slow link downloads fields it never displays, and the server serializes columns no caller reads. Field selection lets the client ask for what it needs, so the payload shrinks and the serialization work drops. The pattern is usually a fields parameter naming the fields to include and an expand parameter naming related resources to include.

This tutorial implements sparse fieldsets and explicit expansions, validates them against an allowlist, pushes the selection into the database projection, and tests both the size and the correctness. The examples use query parameters and a Node.js API, and the design follows the sparse fieldset pattern of JSON:API and the partial-response guidance from API design guides.

Expose fields and expansions explicitly

A fields parameter, such as fields=id,title,created_at, names the fields to include. An expand parameter, such as expand=author,tags, names the related resources to include. Absent parameters fall back to a default set that is sensible for the common case, so a client that does not use the feature still gets a usable response. The default should be the fields most clients want, not every field.

Give expansions a default of none and make them explicit, so a client that does not ask pays nothing for related data. Unbounded, implicit expansion is where over-fetching comes from: include everything related and the payload grows with the data. Explicit expansions keep the client in control and the payload proportional to what it asked for.

// client asks only for what it needs
// GET /articles?fields=id,title,created_at&expand=author
interface Query {
  fields?: string;    // comma-separated sparse fieldset
  expand?: string;    // comma-separated related resources
}

function parseSelection(query: Query, defaults: string[]) {
  const fields = query.fields ? query.fields.split(',').map((f) => f.trim()) : defaults;
  const expand = query.expand ? query.expand.split(',').map((e) => e.trim()) : [];
  return { fields, expand };
}

Validate against an allowlist

A client must not be able to request a field it should not see or an expansion that is expensive or unbounded. Allowlist the selectable fields and the expandable relations, and reject or ignore anything outside the list. If a field such as an internal note or a secret token is not in the selectable list, a request for it cannot expose it, which keeps the field-selection feature from becoming an authorization bypass.

Also bound the expansion depth. Nested expansions such as expand=author.company.address invite an unbounded expansion and a large query. Allow one or two levels, and reject deeper ones, so a client cannot turn a small request into an expensive one. Validation protects both the data and the cost.

const SELECTABLE = new Set(['id', 'title', 'body', 'created_at', 'author_id']);
const EXPANDABLE = new Set(['author', 'tags']);

function validateSelection(fields: string[], expand: string[]) {
  for (const f of fields) if (!SELECTABLE.has(f)) throw new Error('field not selectable: ' + f);
  for (const e of expand) if (!EXPANDABLE.has(e)) throw new Error('expansion not allowed: ' + e);
}

Push the selection into the query

Select only the requested columns in the database query, so unrequested columns are never read from disk, transferred, or serialized. A query that selects every column and then strips fields in the serialization layer wastes the database work and the transfer; selecting the columns up front removes both. Map the requested field names to column names through a fixed dictionary so a client cannot inject a column name.

Expansions become joins or separate batched queries depending on the shape. An expansion with a to-one relation is a join; a to-many expansion is often better as a batched query to avoid row multiplication. Only include the expansions that were asked for, so a request without expansion never joins a related table, which keeps the common case fast.

-- only the requested columns; names mapped from an allowlist, not from raw input
SELECT id, title, created_at
FROM articles
WHERE id = $1;
-- an expand=author adds a join or a batched lookup, only when requested

Keep the response typed and cacheable

Document the default fieldset and let clients rely on it. A response whose fields depend on a parameter is harder to type, so return a documented structure where fields are optional when not selected, and generate client types from the same schema. Where possible, keep a stable default so a client that does not use selection gets a predictable shape.

For caching, recognize that each field combination is a distinct URL and thus a distinct cache key. Cache the default response and the few common selections, and do not try to cache every arbitrary combination, which has a low hit rate and evicts useful entries. A CDN can cache the default, and the selection happens at the origin for the rest, or the origin caches a superset and selects after.

// cache the default response; handle uncommon selections at the origin
res.setHeader('Cache-Control', 'public, max-age=60');   // default fieldset
// a sparse selection with uncommon fields bypasses the shared cache

Test size and correctness

Test that a selected response contains only the requested fields and no others, including when an expansion is omitted. Test that the response is smaller than the default for a small selection. Test that an unselectable field or a disallowed expansion is rejected. Test that the default fieldset is returned when no parameters are sent, so clients that ignore the feature still work.

curl -s 'http://localhost:3000/articles/1?fields=id,title' | node -e 'const d=JSON.parse(require("fs").readFileSync(0));console.log(Object.keys(d))'
# expect only ['id','title']
curl -s -o /dev/null -w '%{http_code}\n' 'http://localhost:3000/articles/1?fields=internal_note'  # 400

Common pitfalls

Returning every field by default so clients over-fetch, allowing any field name so a sensitive field is exposed, unbounded expansion that lets a client make an expensive query, selecting every column then stripping fields in serialization, and caching every field combination so the hit rate collapses are the recurring mistakes. A sensible default, an allowlist, bounded expansions, projection in the query, and selective caching address them.

Conclusion

Field selection shrinks payloads by letting clients ask for what they need. Expose a fields parameter and an explicit expand parameter, validate both against an allowlist with a bounded expansion depth, push the selection into the database projection, and cache only common selections. Self-check by asserting a selected response contains exactly the requested fields and is smaller, and that an unselectable field is rejected. Then bandwidth and serialization scale with what clients use, not with what the object contains.

Sources: JSON:API: Sparse fieldsets, Google API design guide: partial responses, MDN: URLSearchParams.

FAQ

Is field selection worth the complexity?
For APIs serving large objects to many clients with different needs, yes. Returning every field wastes bandwidth and serialization time for clients that use a few. For a small fixed response, the complexity may not pay off, so apply it where over-fetching is real.
Do sparse fieldsets break caching?
They multiply the cache keys, because each field combination is a distinct URL. Cache the common combinations and let the rest fall through, or cache at the level of a fixed default and select fields after. Beware of caching per arbitrary combination, which has a low hit rate.

Related Examples