Expand description
Calling other services in the application.
A Client targets a single service. Because client is const, you
can declare clients as module-level statics:
use encore::services;
static BILLING: services::Client = services::client("billing");
async fn invoices() -> anyhow::Result<Vec<Invoice>> {
Ok(BILLING.get("/invoices").send().await?.error_for_status()?.json().await?)
}Outgoing requests to application services automatically propagate the active
trace context and Request Context (crate::reqctx), so downstream
services continue the same trace and request metadata. Requests to external
origins never include Request Context headers. All Client instances
share a single connection pool, so creating a client on demand is as cheap
as using a static.
For Tower-based HTTP clients (such as hyper-util or a tonic channel),
use PropagateLayer for the same propagation behavior.
Calling base_url or client declares a dependency on the target
service. Because Encore parses dependencies statically from source code,
pass the service name as a string literal, call the function directly
(rather than through a function pointer), and make the call inside a
service.
§Generated clients
When a service lists another service under clients in its
encore.service.json, Encore generates typed clients in
encore_gen::clients — one module per service, containing one module per
declared API. Each operation is a top-level function returning a call builder
that executes when .awaited:
mod encore_gen;
use encore_gen::clients::catalog;
let product = catalog::openapi::get_product("xyz").await?;
let users = catalog::openapi::list_users().limit(10).await?;Failed calls return CallError regardless of API protocol, and ?
converts it into an encore::Error with the same error
code:
let product = match catalog::openapi::get_product("xyz").await {
Ok(product) => Some(product),
Err(err) if err.code == encore::ErrCode::NotFound => None,
Err(err) => return Err(err.into()),
};Use UnlessNotFound to turn a NotFound error into Ok(None):
use encore::services::UnlessNotFound;
let product = catalog::openapi::get_product("xyz").await.unless_not_found()?;For APIs that require a Future directly (such as tokio::spawn or
join_all), call .into_future(). The resulting future captures the
caller’s trace and Request Context just like an awaited call:
use std::future::IntoFuture;
let product = tokio::spawn(catalog::openapi::get_product("xyz").into_future());Individual calls can override timeouts and headers, and each API module
provides a Client for sharing default settings across calls:
let product = catalog::openapi::get_product("xyz")
.timeout(Duration::from_secs(2))
.await?;
let storefront = catalog::storefront::Client::new().header("x-tenant", "a");Generated HTTP/OpenAPI/GraphQL clients use the same shared connection pool
and context propagation as Client. Generated gRPC clients (Unary,
ServerStreaming, ClientStreaming, and BidiStreaming) speak gRPC
over HTTP/2 via tonic, sharing one channel per base URL — using cleartext
HTTP/2 (h2c) for http:// URLs and TLS (trusting system roots or
SSL_CERT_FILE) for https:// URLs.
For gRPC calls, a timeout acts as an end-to-end deadline covering
connecting and every message on a stream. Bidirectional streams resolve
immediately without waiting for server headers so the server can read an
initial client message first. Decoded protobuf messages preserve unknown
fields from newer schemas when re-encoded, and gRPC error details are
exposed on CallError::grpc_details. Because a generated Client only
holds settings, constructing one per call is free and requires no cleanup.
§Tests
In unit tests under encore test, peer services are not started. Every
service still has a placeholder base URL so clients can be constructed, but
calls return 501 Not Implemented identifying the service and path; mock
downstream calls in unit tests (or use system tests).
Re-exports§
pub use reqwest;
Structs§
- Bidi
Streaming - A bidirectional-streaming gRPC call (stream of requests, stream of responses).
- Call
Error - Error returned when a generated service client call fails.
- Client
- HTTP client for calling another service in the application, created with
client. - Client
Streaming - A client-streaming gRPC call (stream of requests, one response message).
- Propagate
- Tower service produced by
PropagateLayer. - Propagate
Layer - Tower
Layerthat propagates the active trace and Request Context on outgoing requests to application services (and strips Request Context headers for all other origins). - Request
Builder - Builder for an HTTP request sent by
Client, wrappingreqwest::RequestBuilderwith Encore context propagation. - Server
Streaming - A server-streaming gRPC call (one request message, stream of responses).
- Streaming
- Stream of response messages from a server-streaming or bidirectional gRPC call.
- Unary
- A unary gRPC call (one request message, one response message).
Traits§
- Stream
- Re-export of
futures_core::Streamused by generated gRPC streaming calls. A stream of values produced asynchronously. - Unless
NotFound - Extension trait that converts a
CallErrorwith codeErrCode::NotFoundintoOk(None).