Skip to main content

HTTP Client

The HTTP client capability allows your application component to make HTTP requests. Whether it's an internal request to another application component, a request sent to a publicly accessible HTTP API, or a simple connectivity check, this capability enables secure network requests for all types of applications. This capability is included as one of the open source wasmCloud interfaces and has the capability contract ID wasmcloud:httpclient.

Using this capability

This capability can be used in your project by adding a dependency on the wasmcloud-interface-httpclient crate, and by adding wasmcloud:httpclient to the capabilities section in your application's wasmcloud.toml file.

cargo add wasmcloud-interface-httpclient

wasmcloud.toml

[actor]
capabilities = ["wasmcloud:httpclient"]

Operations

OperationInputOutput
requestHttpRequestHttpResponse

Example Usage

This sample actor handles HTTP requests by returning a response where the body is an HTTP cat. This actor can easily be modified for different status codes. Note here the use of wasmcloud_interface_httpserver::{HttpRequest as Req} to ensure that the Rust compiler can differentiate between the two interface's conflicting types.

use wasmbus_rpc::actor::prelude::*;
use wasmcloud_interface_httpclient::{HttpClient, HttpClientSender, HttpRequest};
use wasmcloud_interface_httpserver::{HttpRequest as Req, HttpResponse, HttpServer, HttpServerReceiver};

const CAT_STATUS_CODE_PREFIX: &str = "https://http.cat/";

#[derive(Debug, Default, Actor, HealthResponder)]
#[services(Actor, HttpServer)]
struct CatStatusActor {}

#[async_trait]
impl HttpServer for CatStatusActor {
    async fn handle_request(&self, ctx: &Context, _req: &Req) -> RpcResult<HttpResponse> {
        // Create the request object
        let request = HttpRequest::get(&format!("{}/200", CAT_STATUS_CODE_PREFIX));
        // Make an HTTP request, the response body will be image bytes
        let success_cat = HttpClientSender::new().request(ctx, &request).await?;

        Ok(HttpResponse::ok(success_cat.body))
    }
}

Choosing an Implementation

We use the open source wasmCloud implementation of the HTTP client for standard HTTP requests.