Expand description
Outgoing HTTP requests: calling another service’s API from a handler, a job or a scheduled task.
A Request is built step by step (headers, a JSON or form body, a
timeout) and Request::send returns a Send future, so axum handlers
await it directly: no worker::send::SendFuture and no JavaScript types
in the app. Every answer is a Response, whatever its status; turn
the non-2xx ones into errors with Response::error_for_status.
- Requests time out after
DEFAULT_TIMEOUT(30 s) unlesstimeoutsays otherwise; the error then says so. - Redirects are followed unless
follow_redirects(false), for URLs a user typed (webhook endpoints), where a redirect could lead to an address the app refused. - Errors are
Error::Internal(500): the message names the method, the URL without its query string (which may hold credentials) and the cause.
§Free plan
Each send is one subrequest: 50 per invocation on the free plan (1,000
on Workers Paid), counted with the D1, R2 and KV calls. Time spent
waiting for the answer is not CPU time; parsing a JSON answer is (about
1 ms per 100 KB).
§Tests
ocre test runs the app in workerd, which can reach a server the test
starts on 127.0.0.1 (ocre::testing::FakeServer, feature testing).
Point the app at it with a test header read by test_override
(debug builds only), so production code keeps the real URL.
§Examples
use std::time::Duration;
use axum::extract::State;
use ocre::{Ctx, Result, http};
use serde::Deserialize;
#[derive(Deserialize)]
struct Rates {
eur: f64,
}
async fn usd_to_eur(State(ctx): State<Ctx>) -> Result<String> {
let key = ctx.secret("RATES_API_KEY").await?;
let rates: Rates = http::Request::get("https://api.example.com/latest")
.query(&[("base", "usd")])
.bearer(&key)
.timeout(Duration::from_secs(5))
.send()
.await?
.error_for_status()?
.json()?;
Ok(rates.eur.to_string())
}Structs§
- Request
- An outgoing HTTP request, built step by step and sent with
send. - Response
- The answer to a
Request: status, headers and the whole body.
Constants§
- DEFAULT_
TIMEOUT - How long
Request::sendwaits for an answer unlessRequest::timeoutsays otherwise: 30 seconds.
Functions§
- test_
override - The value of the request header
x-ocre-test-<name>in debug builds (ocre dev,ocre test); alwaysNonein release builds.