Calling another service's API
A handler can call another service's HTTP API and answer the browser with what it returned, so the service's address and token stay on the server.
The client in the router's state
The data may belong to another service: a backend another team runs, a SaaS, or a database that answers over HTTP. The browser still calls only this server's actions, and the action's handler calls the service and answers with a Page or Patches built from the reply. The service's address and its token are read from the environment on the server, and no page holds them.
The samples use reqwest with its json feature, which adds RequestBuilder::json and Response::json:
[dependencies]
reqwest = { version = "0.13", default-features = false, features = ["json", "rustls"] }/// The client of the notes service. One `reqwest::Client` keeps a pool of
/// connections, so the router's state holds it and every handler shares it.
#[derive(Clone)]
struct AppState {
client: reqwest::Client,
base: String,
token: String,
}
/// A note as the service's JSON has it.
#[derive(Deserialize)]
struct Note {
text: String,
}
struct ApiError(reqwest::Error);
impl From<reqwest::Error> for ApiError {
fn from(error: reqwest::Error) -> Self {
Self(error)
}
}
impl IntoResponse for ApiError {
fn into_response(self) -> Response {
eprintln!("notes service: {}", self.0);
let message = "The notes service did not answer. Try again.";
(StatusCode::BAD_GATEWAY, message).into_response()
}
}
async fn index(state: AppState, (): ()) -> Result<Page<Notes>, ApiError> {
let notes: Vec<Note> = state
.client
.get(format!("{}/notes", state.base))
.bearer_auth(&state.token)
.send()
.await?
.error_for_status()?
.json()
.await?;
let count = i32::try_from(notes.len()).unwrap_or(i32::MAX);
let list = ul().children(notes.into_iter().map(|note| li().text(note.text)));
Ok(Page::new("Notes", Notes { count }).child(list))
}
hypersig::routes! {
fn pages(Router<AppState>);
const INDEX: Route = "/" => index;
}
let state = AppState {
client: reqwest::Client::new(),
base: std::env::var("API_URL").expect("API_URL names the notes service"),
token: std::env::var("API_TOKEN").expect("API_TOKEN holds its token"),
};
let _app: Router = pages(Router::new()).with_state(state);A reqwest::Client keeps a pool of connections, so build one when the server starts and keep it in the state, in place of one per request. The service's JSON deserializes into a struct with serde, so a reply of another shape fails at json() and goes to the handler's error. error_for_status turns a 4xx or 5xx from the service into an error the same way.
When the service refuses or fails
Tell two kinds of failure apart. A refusal of the visitor's input, such as a 422 with a message, is something the visitor can fix, so answer with that status and the message. Every other failure, such as a service that does not answer, a 5xx, a 401 from a wrong token, or a body that does not parse, is one the visitor can only retry, so log its detail on the server and answer 502 with a message to try again. The api example has an ApiError with one variant for each, and the sample below takes it from there:
#[derive(Signals, Serialize, Deserialize)]
struct Notes {
draft: String,
problem: String,
}
#[derive(Serialize)]
struct NewNote<'a> {
text: &'a str,
}
/// The body of a request the service refused.
#[derive(Deserialize)]
struct Refusal {
error: String,
}
enum ApiError {
/// The service answered 422 about the visitor's input, which the
/// visitor can fix.
Refused(String),
/// Anything else. The visitor can only try again.
Unavailable(String),
}
impl From<reqwest::Error> for ApiError {
fn from(error: reqwest::Error) -> Self {
Self::Unavailable(error.to_string())
}
}
/// The runtime writes this body to the signal given to `Call::error`.
impl IntoResponse for ApiError {
fn into_response(self) -> Response {
match self {
Self::Refused(message) => (StatusCode::UNPROCESSABLE_ENTITY, message).into_response(),
Self::Unavailable(detail) => {
eprintln!("notes service: {detail}");
let message = "The notes service did not answer. Try again.";
(StatusCode::BAD_GATEWAY, message).into_response()
}
}
}
}
async fn add(state: AppState, draft: String) -> Result<Patches<Notes>, ApiError> {
let response = state
.client
.post(format!("{}/notes", state.base))
.bearer_auth(&state.token)
.json(&NewNote { text: &draft })
.send()
.await?;
if response.status() == StatusCode::UNPROCESSABLE_ENTITY {
let refusal: Refusal = response.json().await?;
return Err(ApiError::Refused(refusal.error));
}
response.error_for_status()?;
Ok(Notes::draft().patch(String::new()).into())
}
async fn index(_: AppState, (): ()) -> Page<Notes> {
let signals = Notes { draft: String::new(), problem: String::new() };
Page::new("Notes", signals).child(
form()
.on_submit(ADD.call_with(Notes::draft()).error(Notes::problem()))
.child(input().bind(Notes::draft()))
.child(button().text("Add"))
.child(p().role(Role::Alert).bind_text(Notes::problem())),
)
}
hypersig::routes! {
fn pages(Router<AppState>);
const INDEX: Route = "/" => index;
action ADD: Action<Notes, String> = post "/notes" => add;
}Submitting the form calls ADD with the draft, and the handler passes it to the service. When the service refuses the note, the handler answers the call with the service's message as plain text and the status 422:
HTTP/1.1 422 Unprocessable Entity
content-type: text/plain; charset=utf-8
A note holds 1 to 80 characters.The signal that receives the message
Call::error is fn error(self, message: Sig<S, String>) -> Self. It sets message to "" when the call is sent, and to a text when the call fails. The text depends on what came back:
| What came back | The text in message |
|---|---|
A status outside 2xx with a text/plain body, as axum sends for a String | The body |
| A status outside 2xx with an empty body or one of another type, such as a proxy's HTML error page | The status and its reason, such as 502 Bad Gateway |
| No answer | The browser's message |
The status also goes to the console. The signal holds a String, so a signal of another type fails to compile with E0308:
#[derive(Signals, Serialize, Deserialize)]
struct Notes {
draft: String,
failures: i32,
}
hypersig::routes! {
fn actions(Router<()>);
action ADD: Action<Notes, String> = post "/notes" => add;
}
// `Call::error` writes text, and `failures` holds an `i32`.
let _form = form()
.on_submit(ADD.call_with(Notes::draft()).error(Notes::failures()))
.child(button().text("Add"));Which status the handler picks is not checked. A handler that answered the refusal with a 502 would show the same sentence, and a page that tells the two apart through Call::status would read the wrong one.
api example comes with a stand-in for the service, cargo run -p example-api --bin notes-backend, which keeps notes behind a bearer token and refuses a note longer than 80 characters with a 422. Its end-to-end test checks that the refusal's message reaches the page and that the draft stays.Changes the service makes
An open tab learns of a change only through a stream of this server. Where the service can call a webhook, serve one as an axum route that sends on a broadcast channel in the state, as examples/todo does after each action, and the streams send the item that changed. Where it cannot, a stream can ask the service again after each tokio::time::sleep. The channel reaches only the streams of the process the webhook reached, so with more than one process, carry the change to each of them as Updates with more than one process does.
What the compiler checks
The service's paths and the shape of its JSON are outside what hypersig checks, as a plain SQL string is: a wrong path or field fails when the call runs. Where the service publishes an OpenAPI description, a client generated from it, such as one from the progenitor crate, turns them into Rust types.
On Cloudflare Workers
A worker calls a service with the worker crate's Fetch, or calls another worker through a service binding that env.service returns, in place of reqwest. Its future is not Send, so wrap it in SendFuture, as the Cloudflare template does with its D1 calls.
Next
- Busy and failed calls shows the signals a call sets while it waits and after it fails.
- Streams covers the stream that sends an open tab the changes a webhook reports.
- Signing in keeps who the visitor is in a session, for a service that answers per member.