Skip to content

Calling Other Services with RestTemplate

RestTemplate is Winter Boot’s Spring-style synchronous HTTP client for calling downstream services. It is registered as a default bean, so you can inject it anywhere with #[Autowired] — no configuration class needed:

OrderService.php
<?php
namespace app\service;
use dev\winterframework\stereotype\Service;
use dev\winterframework\stereotype\Autowired;
use dev\winterframework\web\client\RestTemplate;
#[Service]
class OrderService
{
#[Autowired]
private RestTemplate $restTemplate;
public function fetchUser(int $id): array
{
return $this->restTemplate->getForObject(
'https://users.internal/users/{id}',
'array',
['id' => $id]
);
}
}

The bean is preconfigured from winter.rest.* keys (see below), but anything else — a custom User-Agent, basic auth, a custom transport — needs your own bean definition. Declare it in a #[Bean] method and yours wins: the default bean never overrides an application-defined one, so every #[Autowired] RestTemplate then injects yours.

HttpConfig.php
<?php
namespace app\config;
use dev\winterframework\stereotype\Bean;
use dev\winterframework\stereotype\Configuration;
use dev\winterframework\web\client\RestTemplate;
#[Configuration]
class HttpConfig
{
#[Bean]
public function restTemplate(): RestTemplate
{
$template = new RestTemplate(timeout: 3.0, connectTimeout: 1.0);
$template->setDefaultHeader('User-Agent', 'MyApp/1.0');
$template->setBasicAuth('user', 'secret');
return $template;
}
}

Placeholders in {braces} are expanded from the $uriVars argument, and $query entries are merged over any query string already in the URL:

$user = $this->restTemplate->getForObject(
'https://users.internal/users/{id}',
'array',
['id' => 42],
headers: ['X-Trace' => 'abc'],
query: ['verbose' => true]
);
$created = $this->restTemplate->postForObject(
'https://users.internal/users',
['name' => 'ada'] // arrays are JSON-encoded
);
$this->restTemplate->put('https://users.internal/users/{id}', ['name' => 'grace'], ['id' => 7]);
$this->restTemplate->delete('https://users.internal/users/{id}', ['id' => 7]);

For full control (any method, headers plus body), use exchange() with an HttpEntity:

use dev\winterframework\web\client\HttpEntity;
$entity = $this->restTemplate->exchange(
'POST',
'https://users.internal/echo',
HttpEntity::withJsonBody(['a' => 1], ['X-Req' => 'yes'])
);
$status = $entity->getStatus()->getValue(); // 200
$headers = $entity->getHeaders(); // HttpHeaders
$body = $entity->getBody(); // mapped per $responseType

getForEntity() / postForEntity() are shorthand for exchange() with GET / POST, and headForHeaders() returns the response HttpHeaders of a HEAD call.

The $responseType argument controls conversion:

  • 'array' (default): JSON-decoded associative array.
  • 'string': raw body, untouched.
  • A class name: JSON decoded, then mapped via ObjectCreator (honors #[JsonProperty]; see JSON & XML).

An empty body maps to null.

By default, 4xx responses throw HttpClientErrorException and 5xx throw HttpServerErrorException (both extend RestClientException, which is a RuntimeException). The exception carries the status code, response headers, and body via getters; its message contains only the method, the URL without its query string, and the status line, so tokens in query strings or bodies never leak into logs.

use dev\winterframework\web\client\HttpClientErrorException;
try {
$this->restTemplate->getForObject('https://users.internal/users/99');
} catch (HttpClientErrorException $ex) {
$ex->getStatusCode(); // 404
}

To receive error responses as entities instead of exceptions, call $restTemplate->setThrowOnError(false) — the entity then carries the raw string body. For custom handling, setErrorHandler() accepts a fn(string $method, string $url, int $status, string $body, array $headers): void invoked for every 4xx/5xx response. The handler can throw its own exception; if it returns, the call yields an entity with the raw string body (it is never decoded as JSON).

Constructor and setter configuration:

$template = new RestTemplate(timeout: 3.0, connectTimeout: 1.5);
$template->setDefaultHeader('X-Service', 'orders');
$template->setBasicAuth('user', 'secret');

Only http and https URLs are accepted; file://, gopher:// and other schemes are rejected with RestClientException, so a URL built from user input cannot read local files. Still validate hosts yourself when the URL comes from a user (internal addresses are reachable).

Every request also sends Accept: application/json and a browser User-Agent by default (some publishers reject headerless clients with 403); override either per request or via setDefaultHeader(). Header names and values containing CR/LF are rejected outright.

Default-bean timeouts come from application.yml:

winter:
rest:
timeout: 10.0
connect-timeout: 5.0

exchangeStream() (2.3+) decodes the response body as it arrives and hands each item to a callback, instead of returning the body whole: an AI model’s token stream, server-sent events, or JSON lines.

use dev\winterframework\web\client\HttpEntity;
use dev\winterframework\web\client\StreamDecoder;
use dev\winterframework\web\sse\SseEvent;
$result = $this->restTemplate->exchangeStream(
'POST',
'https://api.example.com/v1/chat',
new HttpEntity(['stream' => true, 'messages' => $messages], ['Authorization' => 'Bearer ' . $key]),
function (SseEvent $event) use ($out) {
$out->write($event->json()['delta'] ?? '');
},
decoder: StreamDecoder::sse(),
cancel: $token, // optional: stop the call from elsewhere
);
$result->isCompleted(); // ended normally ([DONE] or the server closed it)

exchangeStream(string $method, string $url, ?HttpEntity $entity, callable $onItem, ?StreamDecoder $decoder = null, ?CancellationToken $cancel = null, array $uriVars = [], array $query = []): StreamExchangeResult

Bytes arrive in arbitrary pieces: an event or a line can be split across two chunks, and one chunk can hold several. The decoder buffers what is incomplete and hands your callback only whole items.

Decoder Callback receives For
StreamDecoder::raw() (default) string, each chunk as it arrives plain text, your own framing
StreamDecoder::sse() SseEvent text/event-stream: OpenAI, Anthropic and most AI APIs
StreamDecoder::ndjson() the decoded JSON value of each line newline-delimited JSON: Ollama and other JSON-lines APIs
  • SSE: parses event:, multi-line data:, id:, retry:, comment lines and any line ending. The data: [DONE] sentinel most AI vendors send ends the stream: it is not delivered, and reading stops there. Keep the decoder to resume later: $sse = StreamDecoder::sse(); …; $sse->getLastEventId().
  • NDJSON: skips empty lines, and delivers a last line without a newline when the body ends. A line over 4 MiB (StreamDecoder::ndjson($maxLineBytes)) or invalid JSON fails the call.
  • Your own: extend StreamDecoder and implement feed(string $bytes): iterable (plus finish() and isDone() if the format needs them). Use a new decoder for every call; they keep state.

Malformed input throws StreamDecodeException (a RestClientException); its message names the call, never body content. An exception thrown by your callback is passed through unchanged.

SseEvent, SseParser and the server-side SseEmitter share the dev\winterframework\web\sse namespace: an event parsed here can be re-emitted as is with SseEmitter::send().

  • From the callback: return false. Reading stops and the connection closes without an error; the result reports isAborted().
  • From elsewhere: pass a CancellationToken (dev\winterframework\util\concurrent) as cancel:. Within about 100 ms of cancel() the call returns, also while the server sends nothing: a “stop” button works while the model is still thinking. The result reports isCancelled(). A cancelled token passed in makes no request at all.
  • Neither is an error.

Two tokens come ready-made: WebSocketSession::beginWork() (cancelled by a “stop” message or the socket closing) and ResponseWriter::getCancellationToken() (cancelled when your own client disconnects).

StreamExchangeResult extends ResponseEntity (status and headers) and reports how the stream ended: isCompleted(), isAborted(), isCancelled(), plus getBytesReceived() and getItemsDelivered(). Its body is null: the content went to your callback.

  • The status and headers are known before the first byte. A 4xx/5xx response never reaches the callback: its body (up to 1 MiB) is mapped exactly like exchange(), to HttpClientErrorException / HttpServerErrorException with getResponseBody(), or to your error handler.
  • Stream idle timeout: the longest silence between two reads, not a total budget, so a stream may run for any length of time as long as data keeps coming. Default 60 s, because AI models can think for a while before the first token: setStreamIdleTimeout() or winter.rest.stream-idle-timeout. setTimeout() (the total for exchange()) does not apply to streams. The connect timeout applies as usual. Exceeding either throws RestClientTimeoutException; the message never contains the query string.
  • Inside a Swoole coroutine it never blocks the worker, whatever hook_flags say (-SWOOLE_HOOK_CURL included): it speaks HTTP/1.1 over Swoole’s coroutine socket, not cURL. Outside coroutines it uses PHP sockets. Redirects are not followed, and Accept-Encoding: identity is always requested.
  • HTTPS is verified against the system CAs (or the caFile given to DefaultRestClientTransport). With a proxy (new DefaultRestClientTransport(proxy: 'http://user:pass@proxy:3128')), HTTPS goes through a CONNECT tunnel.

RestTemplate delegates I/O to a RestClientTransport. The default transport picks its engine at runtime: Swoole’s coroutine HTTP client inside a coroutine, cURL when available, plain PHP streams otherwise — so the same bean works from request handlers, CLI commands, and tests. Streaming calls need a transport that also implements StreamingRestClientTransport (the default one does); with any other transport exchangeStream() still works, but the whole body arrives as one chunk.

Unit tests should inject a fake transport instead of touching the network:

$fake = new FakeTransport(); // your RestClientTransport implementation
$template = new RestTemplate($fake);

To test code that uses exchangeStream(), give the fake StreamingRestClientTransport as well, so it delivers the body in the chunks you choose (split an SSE event across two chunks to test your parsing):

use dev\winterframework\web\client\RestClientTransport;
use dev\winterframework\web\client\StreamingRestClientTransport;
use dev\winterframework\web\client\StreamRequest;
final class FakeStreamingTransport implements RestClientTransport, StreamingRestClientTransport
{
/** @param string[] $chunks */
public function __construct(private int $status, private array $chunks) {}
public function request(string $method, string $url, array $headers, ?string $body, float $timeout, float $connectTimeout): array
{
return ['status' => $this->status, 'headers' => [], 'body' => implode('', $this->chunks)];
}
public function stream(StreamRequest $request, callable $onResponse, callable $onChunk): void
{
$onResponse($this->status, ['Content-Type' => ['text/event-stream']]);
foreach ($this->chunks as $chunk) {
if ($request->isCancelled() || $onChunk($chunk) === false) {
return; // the caller stopped
}
}
}
}
$rest = new RestTemplate(new FakeStreamingTransport(200, ["data: {\"text\":\"Hel", "lo\"}\n\n", "data: [DONE]\n\n"]));

StreamRequest carries what RestTemplate prepared: method, url, headers, body, idleTimeout, connectTimeout and the cancel token. New options are added there, so a transport’s stream() signature never changes.

A fake that implements only RestClientTransport still works with exchangeStream(): the whole body is decoded at once after it arrived.