Welcome to the new Golem Cloud Docs! 👋
Documentation
Rust Language Guide
HTTP client

HTTP requests in Rust

Golem implements the WASI HTTP (opens in a new tab) interfaces so any library built on this specification can be used from Golem components to communicate with external services.

Currently there is only one such Rust library available, a fork of the popular reqwest library provided by the Golem team: https://github.com/golemcloud/reqwest/tree/update-jun-2024 (opens in a new tab)

Adding as a dependency

To use it, add the following dependency to your component's Cargo.toml:

[dependencies]
reqwest = { git = "https://github.com/golemcloud/reqwest", branch = "update-jun-2024", features = ["json"] }

Optionally add serde and serde_json to take advantage of reqwest's JSON support:

serde = { version = "1.0.203", features = ["derive"] }
serde_json = "1.0.117"

Making a request

The fork provides the same API as the official reqwest library's blocking API, documented here (opens in a new tab).

In the following example we make a POST request sending a JSON payload and parsing the response as JSON using derived codecs by serde.

First let's define the request and response body types:

use serde::{Deserialize, Serialize};
 
#[derive(Clone, Debug, Serialize, Deserialize)]
struct ExampleRequest {
    name: String,
    amount: u32,
    comments: Vec<String>,
}
 
#[derive(Clone, Debug, Serialize, Deserialize)]
struct ExampleResponse {
    percentage: f64,
    message: Option<String>,
}

Then in the worker's implementation we can use reqwest in the following way (proper error handling omitted for brevity):

use reqwest::*;
 
// ...
 
let client = Client::builder().build().expect("Failed to create client");
 
let request_body = ExampleRequest {
    name: "Something".to_string(),
    amount: 42,
    comments: vec!["Hello".to_string(), "World".to_string()],
};
 
let response: Response = client
    .post(&format!("http://example.com:8080/post-example"))
    .json(&request_body)
    .header("X-Test", "Golem")
    .basic_auth("some", Some("body"))
    .send()
    .expect("Request failed");
 
let status = response.status();
let body = response
    .json::<ExampleResponse>()
    .expect("Invalid response");
 
println!("Received {:?} {:?}", status, body);