use playwright_rs::protocol::Playwright;
use playwright_rs::{APIRequestContextOptions, FetchOptions};
use serde::Deserialize;
use std::collections::HashMap;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("=== playwright.request() — headless API testing ===\n");
let playwright = Playwright::launch().await?;
let ctx = playwright
.request()
.new_context(Some(APIRequestContextOptions {
base_url: Some("https://httpbin.org".to_string()),
..Default::default()
}))
.await?;
println!(">> GET /get");
let response = ctx.get("/get", None).await?;
println!(
" status: {} {}",
response.status(),
response.status_text()
);
assert!(response.ok());
#[derive(Deserialize, Debug)]
struct HttpBinGet {
url: String,
#[serde(default)]
headers: HashMap<String, String>,
}
let body: HttpBinGet = response.json().await?;
println!(" echoed url: {}", body.url);
println!(" echoed header count: {}", body.headers.len());
println!("\n>> POST /post with JSON body");
let mut headers = HashMap::new();
headers.insert("x-test-header".to_string(), "playwright-rust".to_string());
headers.insert("content-type".to_string(), "application/json".to_string());
let opts = FetchOptions::builder()
.headers(headers)
.post_data(r#"{"hello":"world"}"#.to_string())
.build();
let response = ctx.post("/post", Some(opts)).await?;
println!(" status: {}", response.status());
let text = response.text().await?;
println!(" response length: {} bytes", text.len());
println!("\n>> PUT /put");
let response = ctx.put("/put", None).await?;
println!(" status: {}", response.status());
println!("\n>> DELETE /delete");
let response = ctx.delete("/delete", None).await?;
println!(" status: {}", response.status());
println!("\n>> HEAD /get");
let response = ctx.head("/get", None).await?;
println!(" status: {}", response.status());
if let Some(length) = response.headers().get("content-length") {
println!(" content-length header: {}", length);
}
println!("\n>> fetch() with timeout + max_redirects");
let opts = FetchOptions::builder()
.method("GET".to_string())
.max_redirects(5)
.timeout(10_000.0)
.build();
let response = ctx
.fetch("https://httpbin.org/redirect/2", Some(opts))
.await?;
println!(" final status: {}", response.status());
println!(" final url: {}", response.url());
ctx.dispose().await?;
println!("\nDisposed request context.");
playwright.shutdown().await?;
Ok(())
}