Using HTTP Prefer to choose the response body when creating a report
Try the optional response preferences from RFC 7240 in a report creation endpoint. Three local HTTP requests exercise the same creation contract with different response shapes.
Archive retrospective · Topic year 2014
In this article
Creation and representation are separate decisions
When someone creates a report, the server assigns it an identifier and gives the client a way to refer to it. The response can also contain the initial representation. An administrative screen may want that document immediately so it can add a row. A nightly import may only record the address for a later step. Both clients can use the same creation endpoint. RFC 7240, published in 2014, defines the HTTP Prefer field for communicating optional preferences like these. That leaves teams with one creation operation and an independently testable choice about the reply. The location remains useful to the client that skips the representation, particularly when later reads use a different request or authorization context.
How the client states a preference
The standard treats preferences as optional behavior the server can apply while processing a request. The local example recognizes return=minimal. When the server applies it, the reply preserves status 201 and Location, sends no body, and identifies the applied preference in Preference-Applied. The outgoing header is no evidence on its own that a report exists. The client first reads the HTTP outcome and its creation contract, then considers the applied preference. Consequently, a client should choose whether to parse JSON based on the reply it received. RFC 7240 also defines return=representation for a client that prefers the current representation after a successful operation. The sample already returns a representation by default.
Running three requests against a local server
The example starts a short-lived Node.js HTTP server on the loopback address and lets the operating system select an available port. The first request creates a report using the default response. The second requests the minimal result. The third sends wait=1 and demonstrates that the server can complete the action without applying that preference. The example matches one whole field value. A production parser that supports the broader syntax would also account for multiple preferences, parameters and whitespace. The test uses a contemporary Node runtime and real HTTP requests to demonstrate the 2014 contract. The sample keeps its identifier counter only in process memory, so each run starts with the same initial state.
import assert from 'node:assert/strict';
import { createServer } from 'node:http';
import { once } from 'node:events';
let nextId = 0;
const server = createServer((request, response) => {
if (request.method !== 'POST' || request.url !== '/reports') {
response.writeHead(404).end();
return;
}
const id = ++nextId;
const location = '/reports/' + id;
const headers = { Location: location, 'Cache-Control': 'no-store' };
// The sample recognizes one exact preference, not the full RFC grammar.
if (request.headers.prefer === 'return=minimal') {
response.writeHead(201, { ...headers, 'Preference-Applied': 'return=minimal' }).end();
return;
}
response.writeHead(201, { ...headers, 'Content-Type': 'application/json' });
response.end(JSON.stringify({ id, location }));
});
server.listen(0, '127.0.0.1');
await once(server, 'listening');
try {
const endpoint = 'http://127.0.0.1:' + server.address().port + '/reports';
const results = [];
for (const prefer of ['', 'return=minimal', 'wait=1']) {
const response = await fetch(endpoint, {
method: 'POST',
headers: prefer ? { Prefer: prefer } : {},
});
results.push({
prefer, status: response.status, location: response.headers.get('location'),
applied: response.headers.get('preference-applied'), body: await response.text(),
});
}
assert.deepEqual(results, [
{ prefer: '', status: 201, location: '/reports/1', applied: null, body: '{"id":1,"location":"/reports/1"}' },
{ prefer: 'return=minimal', status: 201, location: '/reports/2', applied: 'return=minimal', body: '' },
{ prefer: 'wait=1', status: 201, location: '/reports/3', applied: null, body: '{"id":3,"location":"/reports/3"}' },
]);
console.log(JSON.stringify({ node: process.version, results }, null, 2));
} finally {
server.close();
}
Reading the output
The first operation returns status 201, Location /reports/1 and a JSON body with id and location. The second still returns 201 and its own Location, /reports/2. Its body is empty and Preference-Applied identifies return=minimal. The third reply points to /reports/3 and contains JSON, with no applied-preference field. Every POST in this test creates a different record. Reissuing the operation after a disconnected response could create another record in this example. A service that needs to resolve such uncertainty needs an operation identifier or a separate idempotency contract. The representation preference controls response handling and cannot answer which request was committed.
Gateways and cached representations
In an environment with a gateway, exercise the remote path as well as the endpoint. The inbound preference needs to reach the handler, and the applied-preference field should reach the client when the handler sends it. This example sends no-store on its POST responses. When a cacheable read can change representation according to Prefer, RFC 7240's Vary requirements matter. A response to a request without the header also needs to remain distinct if the representation can vary. Consider a read endpoint that returns a short version on request. Testing two requests against the same URL through the gateway can reveal whether a cache accidentally replays the short version to a client expecting the full representation.
Measuring a client rollout
Start by checking that the existing client observes the expected status, Location and JSON fields. Then enable return=minimal in a consumer that only needs the address and check its observed response length and applied-preference field. Also exercise the path in which a server ignores the preference. A successful default response should still satisfy the creation contract. If older clients always parse JSON, update their handling before making them ask for an empty reply. Tracking the number of created records and client parsing errors during the same release helps distinguish successful response reduction from a broken integration. Check the server outcome, the actual reply and the client decision separately, since each can fail independently at a different boundary in the request path.
Reader discussion
How would you measure this development's real-world impact?
No comments yet. Be the first to contribute.
Write a comment