http_fetch

Function http_fetch 

Source
pub fn http_fetch<URL: ToString>(
    url: URL,
    options: Option<HttpFetchOptions>,
) -> HttpFetchResponse
Expand description

Performs an HTTP fetch request with the given URL and options. This wraps the unsafe FFI call to the VM’s http_fetch function.

§Panics

Panics if the serialization of the HttpFetchAction fails or if the deserialization of the response fails. We expect these to never happen in practice, as the SDK is designed to ensure valid inputs.

§Examples

use seda_sdk_rs::{bytes::ToBytes, http::{http_fetch, HttpFetchMethod, HttpFetchOptions}};
use std::collections::BTreeMap;

// Basic GET request
let response = http_fetch("https://api.example.com/data", None);
if response.is_ok() {
    println!("Status: {}", response.status);
    println!("Body length: {}", response.content_length);
}

// POST request with JSON payload
let mut headers = BTreeMap::new();
headers.insert("Content-Type".to_string(), "application/json".to_string());

let options = HttpFetchOptions {
    method: HttpFetchMethod::Post,
    headers,
    body: Some(serde_json::to_vec(&serde_json::json!({"temperature": 25.5, "unit": "celsius"})).unwrap().to_bytes()),
    timeout_ms: Some(5_000),
};

let response = http_fetch("https://weather-api.example.com/update", Some(options));

// Handle the response
if response.is_ok() {
    // Access response data
    println!("Status code: {}", response.status);
    println!("Final URL: {}", response.url);
    println!("Response size: {}", response.content_length);

    // Process response headers
    if let Some(content_type) = response.headers.get("content-type") {
        println!("Content-Type: {}", content_type);
    }

    // Process response body
    if !response.bytes.is_empty() {
        // Convert bytes to string if it's UTF-8 encoded
        if let Ok(body_text) = String::from_utf8(response.bytes.clone()) {
            println!("Response body: {}", body_text);
        }
    }
} else {
    println!("Request failed with status: {}", response.status);
}