patterntypescriptTip
Sparse Fieldsets: Allow clients to request only the fields they need
Viewed 0 times
fieldsprojectionsparsefieldsetbandwidthperformancejson-api
Problem
APIs that always return full resource representations waste bandwidth, especially on mobile clients or when only a few fields are needed for a list view. Over-fetching is a common REST pain point.
Solution
Support a fields query parameter: GET /users?fields=id,name,email. Parse the comma-separated list, whitelist against allowed fields, and project only those fields in the response. JSON:API formalizes this as fields[resourceType]=field1,field2.
Why
Sparse fieldsets reduce payload size, improve perceived latency, and reduce the need for specialized summary endpoints. They give clients control without requiring new server endpoints.
Gotchas
- Always include the resource ID even if not requested — clients need it for identity.
- Never allow fields to bypass authorization — a restricted field should remain hidden regardless of fieldset.
- Sparse fieldsets can complicate caching if the cache key does not include the fields parameter.
Code Snippets
Sparse fieldset projection helper
const ALLOWED_FIELDS: (keyof User)[] = ['id', 'name', 'email', 'role', 'createdAt']
function projectFields<T extends Record<string, unknown>>(obj: T, fieldsParam?: string): Partial<T> {
if (!fieldsParam) return obj
const requested = fieldsParam.split(',').map(f => f.trim())
const allowed = requested.filter(f => ALLOWED_FIELDS.includes(f as keyof User))
// Always include id
if (!allowed.includes('id')) allowed.unshift('id')
return Object.fromEntries(allowed.map(f => [f, obj[f]])) as Partial<T>
}Revisions (0)
No revisions yet.