API-94Optional
Let clients ask for only the fields they need
When records carry large or costly fields, let clients pick the fields to return with one fields parameter. Let them embed related records with one expand parameter, capped at one level.
How to do it
A mobile list that needs a name and a price should not download every description and image. Return all fields when fields is missing, so old clients keep working. Answer 400 for an unknown field name rather than ignoring it. Check access for each expanded record as for a direct read, as Authorise every object says. Expansion multiplies the work of one call, so count each expanded record against the page cap in Cap the page size. Keep the field list in the cache key from Set caching headers on every response.
Examples
JavaScript example
const PRODUCT_FIELDS = new Set(['id', 'name', 'price', 'description', 'images']);
export function pickFields(record, fieldsParam) {
if (!fieldsParam) return record;
const wanted = fieldsParam.split(',');
const unknown = wanted.filter(field => !PRODUCT_FIELDS.has(field));
if (unknown.length) throw new BadRequest(`unknown fields: ${unknown.join(', ')}`);
return Object.fromEntries(wanted.map(field => [field, record[field]]));
}
Python example
PRODUCT_FIELDS = frozenset({"id", "name", "price", "description", "images"})
def pick_fields(record: dict, fields_param: str | None) -> dict:
if not fields_param:
return record
wanted = fields_param.split(",")
unknown = [field for field in wanted if field not in PRODUCT_FIELDS]
if unknown:
raise BadRequest(f"unknown fields: {', '.join(unknown)}")
return {field: record[field] for field in wanted}
How to check
GET /products?fields=id,name returns objects with only those two fields. GET /products?fields=nope answers 400. GET /orders?expand=customer.company answers 400, since it asks for two levels.
Sources
Related rules
- API-40 Authorise every object in API design
- API-22 Cap the page size in API design
- API-14 Set caching headers on every response in API design
For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/api-design/requests-and-responses/partial-responses">Agent Wranglers API design playbook</a>. In code you write, add a comment next to it with the same link.