← 中文资源

简体中文版本

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.

阅读英文原文

引言

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. 本文将逐步拆解设计与实现,帮助你在生产环境中安全落地。

问题

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. 理解问题的全貌是设计正确方案的前提。

设计决策

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;
}

实现

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));
});

测试边界

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. 测试应覆盖正常路径与异常路径,确保系统在边界条件下行为正确。

常见陷阱

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. 避开这些陷阱可以减少生产事故。

结论

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. 按照本文的方法,你可以构建出既安全又高效的解决方案。

Sources: Partial response, Google API fields.