Polski

HTTP request builder

A fluent builder for an immutable HTTP request – defaults, header normalisation, validation in build() and a reusable builder.

easy · typescript · javascript · python · csharp · java · go · 10 XP

The shop's HTTP client has a six-parameter constructor, half of which are often null: new HttpRequest('POST', url, null, body, null, 5000). Nobody remembers the order, and invalid combinations (GET with a body, a negative timeout) only show up in production. The Builder pattern separates assembling an object step by step from the result: the code reads like a sentence and the finished request is immutable and always valid.

Task

  1. The builder (RequestBuilder(url); in Java HttpRequest.builder(url)) has defaults: method GET, no headers, no body, a 30 s timeout. Every step returns the same builder:

    • method(m) – case-insensitive, stored upper-case (post → POST);
    • header(name, value) – names stored lower-case, the last value wins;
    • bearerToken(token) – a shortcut for the authorization: Bearer <token> header;
    • body(text) and timeout(...).
  2. build() checks the state in this order and fails with the message:

    • URL must start with http:// or https://,
    • Unsupported method: <M> (allowed: GET, POST, PUT, PATCH, DELETE),
    • <M> request cannot have a body (for GET and DELETE),
    • Timeout must be positive.

    The builder steps themselves validate nothing – the error appears only in build().

  3. The result is immutable: neither the fields nor the headers of a finished request can change, and further calls on the builder do not affect requests built earlier. Every build() creates a new object.

Language details: TypeScript/JavaScript – Object.freeze, timeout(ms), an Error; Python – @dataclass(frozen=True), headers as a MappingProxyType, bearer_token, ValueError; C# – IReadOnlyDictionary (for example ReadOnlyDictionary), Timeout(TimeSpan), InvalidOperationException; Java – the static nested class HttpRequest.Builder, Collections.unmodifiableMap, body() returns Optional<String>, IllegalStateException; Go – unexported fields with accessor methods, Headers() returns a copy, Build() (*Request, error), lower-case error messages per Go convention (url must start with…, timeout must be positive).

Topics: Builder

Related articles

  • Builder – complex objects step by step

    Builder collects an object's parameters in readable steps and hands over a finished, valid product only in build(). A catering order example in C#, TypeScript, Java, Go and Python.