How to Implement Partial Responses for APIs
Let clients select specific fields via a fields query parameter, reducing payload size and improving latency for mobile and edge clients.
On this page
Introduction
A REST API that always returns the full object wastes bandwidth when the client only needs two fields. Mobile apps, edge functions, and dashboards often need a subset of the data, and sending the full payload adds latency and cost. Partial responses let the client specify which fields it wants, and the server returns only those. This guide implements a fields query parameter that parses, validates, and projects the response.
The problem
Without partial responses, every client downloads the full object even if it uses one field. Over-fetching increases response time, bandwidth, and parsing cost on the client. It also makes the API brittle: adding a field increases every response size, even for clients that do not need it. Partial responses solve this by letting the client declare its needs.
Design decisions
The fields parameter is a comma-separated list of field names, with dot notation for nested fields. The parser splits the parameter into a set of paths. The validator checks each path against the response schema and rejects unknown fields with a 400 error. The projector walks the response object and keeps only the fields in the set, preserving the structure. If no fields parameter is present, the full response is returned.
function parseFields(param) {
if (!param) return null;
const fields = new Set(param.split(',').map(f => f.trim()));
return fields;
}
function project(obj, fields) {
if (!fields) return obj;
const result = {};
for (const key of Object.keys(obj)) {
if (fields.has(key)) result[key] = obj[key];
}
return result;
}
Implementation
For nested fields, the projector splits each requested path by dot and walks the response object. For a path like address.city, it keeps address but only the city key inside it. The validator checks each top-level field against the schema properties; unknown fields return a 400 with a message naming the invalid field. The cache key includes the fields parameter so different selections are cached separately. The projector runs after the handler and before serialization.
app.get('/users/:id', async (req, res) => {
const user = await getUser(req.params.id);
const fields = parseFields(req.query.fields);
if (fields) validateFields(fields, userSchema);
res.json(project(user, fields));
});
Testing the boundary
Test that a request with no fields parameter returns the full object. Test that fields=id,name returns only those two fields. Test that fields=name,address.city returns the name and the city inside address. Test that an invalid field name returns a 400 with a clear error message. Test that the response size is smaller with partial selection.
Common pitfalls
Avoid allowing arbitrary field selection without validation; it can expose sensitive fields. Avoid deep nesting in the fields parameter; cap the depth to prevent abuse. Avoid projecting after serialization; project the object before JSON.stringify to avoid double work. Avoid ignoring the fields parameter in the cache key; different selections must not share a cache entry.
Operational considerations
Parse the fields parameter into a field tree before serialization, so the serializer can walk the tree and skip branches the client did not request. A flat comma-separated list like title,author.name,author.id parses into a tree with author as a node and name and id as its children. Store the tree in the request context and pass it to the serializer, not to the model, so the model stays unaware of the projection and the serialization layer owns the filtering. This keeps the model reusable across endpoints that may not support partial responses.
Validate every requested field against the schema and reject unknown fields with a 400, not a silent skip. A silent skip hides typos: a client requesting titel instead of title gets a response without the field and does not notice the miss until a user reports missing data. A 400 with a message listing the unknown fields fails fast and tells the client exactly what to fix. In a strict mode, every unknown field is an error; in a lenient mode, unknown fields are warnings in a response header, so a client can opt to see them without failing the request.
Nest the fields syntax to any depth, but cap the depth to prevent a pathological query like a.b.c.d.e.f.g.h from forcing a deeply recursive serialization. A depth limit of eight covers realistic API shapes and stops abuse. Also cap the total number of fields in one request, because a client that lists a thousand fields is effectively requesting the full payload and loses the benefit of partial responses. A limit of 100 fields is generous for real clients and stops the edge case.
Include the fields parameter in the cache key for the response, so two clients requesting different fields get different cache entries. Without the parameter in the key, a client requesting title could receive a cached entry built for a client that requested title,body, and the extra field would leak. The cache key should also normalize the fields list, so title,author and author,title share an entry. Monitor the cardinality of fields combinations, because a high cardinality means the cache hit rate is low and the partial response feature is not reducing payload enough to justify the parsing overhead.
Conclusion
Partial responses reduce payload size and latency by letting clients select fields. Parse the fields parameter, validate against the schema, project the response, and include the parameter in the cache key. Test full and partial responses, nested selection, and invalid field rejection. The result is an API that sends only what the client needs. For GraphQL APIs, field selection is built into the query language, so the fields parameter pattern is specific to REST endpoints where the client cannot otherwise express a projection.
Sources: Partial response, Google API fields.
FAQ
- Does this work with nested objects?
- Yes. Use dot notation like fields=id,name,address.city to select nested fields; the projector walks the path and keeps only the specified leaves.
- Should I support GraphQL-style queries?
- Not in a REST API; the fields parameter is simpler and sufficient for most cases. Use GraphQL if clients need complex nesting.
- How do I cache partial responses?
- Include the fields parameter in the cache key so different field selections get separate cache entries.
Report a problem with this articleOpens a pre-filled issue on GitHub.