httpx2's way of writing HTTP calls for MoonBit, on gaato/mttp: verb functions, a client with defaults, responses as values, raise_for_status, streaming, event hooks and a mock transport that runs an mttp server handler.
Status: unofficial and experimental. While the version is 0.x, a minor release may contain breaking changes; the changelog lists each one with a migration note.
moon add gaato/requesto///|
#derive(FromJson)
struct Account {
id : Int32
name : String
}
///|
pub async fn example() -> Unit raise @requesto.HTTPError {
let client = @requesto.Client::new(
base_url="https://api.example.com/v1",
headers=[("Accept", "application/json")],
auth=Bearer("token"),
)
defer client.close()
let user : Account = client
.get("users/42", params=[("expand", "teams")])
.raise_for_status()
.json_as()
println("user \{user.id}: \{user.name}")
client.post("users", json={ "name": user.name }) |> ignore
}///|
pub async fn upload(
client : @requesto.Client,
) -> Unit raise @requesto.HTTPError {
client
.post(
"reports",
data=[("title", "weekly")],
files=[@requesto.Part::file("file", "week.csv", "text/csv", b"a,b\n")],
auth=Digest("user", "password"),
)
.raise_for_status()
|> ignore
}///|
pub async fn follow(client : @requesto.Client) -> Unit {
client.stream("GET", "events", async fn(response) {
response.raise_for_status() |> ignore
response.each_event(event => println("\{event.event}: \{event.data}"))
})
}///|
fn hello_app(_ : @mttp.Request) -> @mttp.Response {
@mttp.Response::new(200, body=Bytes(b"hello"))
}
///|
async test "the app answers" {
let client = @requesto.Client::new(
transport=@requesto.MockTransport::new(req => hello_app(req)),
)
defer client.close()
assert_eq(client.get("https://app.test/").text(), "hello")
}| httpx2 | requesto |
|---|---|
| httpx2.get(url, params=..., headers=...) | @requesto.get(url, params=[...], headers=[...]) |
| httpx2.Client(base_url=..., auth=...) | @requesto.Client::new(base_url=..., auth=Bearer(...)) |
| content=b"..." / content="..." | content=b"..." / text="..." |
| r.status_code, r.text, r.json() | r.status_code, r.text(), r.json(), or r.json_as() into a type |
| with client.stream(...) as r: | client.stream(..., async fn(r) { ... }) |
| r.iter_bytes(), r.iter_lines() | r.each_bytes(f), r.each_line(f) |
| httpx_sse's iter_sse() | r.each_event(f) |
| files={"file": ("a.csv", data, "text/csv")} | files=[Part::file("file", "a.csv", "text/csv", data)] |
| auth=("user", "pw"), DigestAuth("user", "pw") | auth=Basic("user", "pw"), auth=Digest("user", "pw") |
| Limits(max_connections=100) | limits=Limits::new(max_connections=Some(100)) |
| proxy="http://...", trust_env=False | proxy="http://...", trust_env=false |
| verify=False, verify="ca.pem" | trust=Insecure, trust=PemFile("ca.pem") |
| Timeout(10.0, connect=5.0) | Timeout::new(Some(10_000), connect=Some(5_000)) (milliseconds) |
| event_hooks={"request": [...], "response": [...]} | event_hooks=EventHooks::new(request=[...], response=[...]) |
| MockTransport(handler) | MockTransport::new(handler) |
| except httpx2.HTTPError | catch { e => ... } on HTTPError |
pub(all) suberror HTTPError {
ConnectTimeout(TransportError)
ReadTimeout(TransportError)
WriteTimeout(TransportError)
PoolTimeout(TransportError)
TotalTimeout(TransportError)
ConnectError(TransportError)
ReadError(TransportError)
WriteError(TransportError)
ProtocolError(TransportError)
ProxyError(TransportError, status~ : Int)
TooManyRedirects(TransportError)
RedirectRefused(TransportError)
TooLarge(TransportError, limit~ : Int)
InvalidRequest(TransportError)
StreamClosed(TransportError)
TransportError(TransportError)
HTTPStatusError(Response)
DecodingError(String)
}pub(all) enum Auth {
Basic(String, String)
Bearer(String)
Digest(String, String)
}pub struct Client {
// private fields
}fn Client::new(base_url? : String, headers? : Array[(String, String)], params? : Array[(String, String)], cookies? : Bool, cookie_jar? : CookieJar, auth? : Auth, timeout? : Timeout, follow_redirects? : Bool, max_redirects? : Int, retry? : RetryPolicy, max_body_bytes? : Int, total_timeout? : Int, event_hooks? : EventHooks, limits? : Limits, proxy? : String, trust_env? : Bool, trust? : Trust, transport? : &Backend, clock? : &Clock, timer? : &Timer) -> Clientasync fn Client::request(self : Client, verb : String, url : String, params? : Array[(String, String)], headers? : Array[(String, String)], content? : Bytes, text? : String, data? : Array[(String, String)], files? : Array[Part], json? : Json, auth? : Auth, follow_redirects? : Bool) -> Response raise HTTPErrorasync fn[T] Client::stream(self : Client, verb : String, url : String, f : async (StreamResponse) -> T, params? : Array[(String, String)], headers? : Array[(String, String)], content? : Bytes, text? : String, data? : Array[(String, String)], files? : Array[Part], json? : Json, auth? : Auth, follow_redirects? : Bool) -> Tfn EventHooks::new(request? : Array[(Request) -> Unit raise HTTPError], response? : Array[(Response) -> Unit raise HTTPError]) -> EventHookspub(all) struct Limits {
max_connections : Int?
max_keepalive_connections : Int
keepalive_expiry : Int
}pub struct MockTransport {
// private fields
}impl Backend for MockTransportasync fn send(self : MockTransport, request : Request, options : SendOptions) -> Response raise TransportErrorasync fn MockTransport::send(self : MockTransport, request : Request, options : SendOptions) -> Response raise TransportErrorpub struct Response {
status_code : Int
headers : Headers
url : String
content : Bytes
request : RequestHead
history : Array[RedirectHop]
elapsed : Int64
}pub struct StreamResponse {
status_code : Int
headers : Headers
url : String
request : RequestHead
// private fields
}async fn StreamResponse::each_event(self : StreamResponse, f : async (SseEvent) -> Unit, max_event_bytes? : Int) -> Unitasync fn StreamResponse::each_line(self : StreamResponse, f : async (String) -> Unit, max_line_bytes? : Int) -> Unitpub(all) struct Timeout {
connect : Int?
read : Int?
write : Int?
pool : Int?
}async fn request(verb : String, url : String, params? : Array[(String, String)], headers? : Array[(String, String)], content? : Bytes, text? : String, data? : Array[(String, String)], files? : Array[Part], json? : Json, auth? : Auth, follow_redirects? : Bool, timeout? : Timeout) -> Response raise HTTPErrorasync fn[T] stream(verb : String, url : String, f : async (StreamResponse) -> T, params? : Array[(String, String)], headers? : Array[(String, String)], content? : Bytes, text? : String, data? : Array[(String, String)], files? : Array[Part], json? : Json, auth? : Auth, follow_redirects? : Bool, timeout? : Timeout) -> TInstall
Download ziphttpx2's way of writing HTTP calls for MoonBit, on gaato/mttp: verb functions, a client with defaults, responses as values, raise_for_status, streaming, event hooks and a mock transport that runs an mttp server handler.