Crate fetchttp

Source
Expand description

§fetchttp

A WHATWG Fetch API compliant HTTP client library for Rust.

This library provides a familiar fetch() API that closely follows the WHATWG Fetch specification, making it easy for developers familiar with web APIs to use in Rust applications.

§Features

  • Specification Compliant: Implements the WHATWG Fetch API specification
  • Async/Await Support: Built on Tokio for modern async Rust
  • Type Safety: Leverages Rust’s type system for safe HTTP operations
  • JSON Support: Built-in JSON serialization/deserialization with serde
  • Flexible Bodies: Support for text, bytes, and JSON request/response bodies
  • Header Management: Complete header manipulation API
  • Request/Response Cloning: Efficient cloning following the specification
  • Abort Signals: Request cancellation support

§Quick Start

§Simple GET Request

use fetchttp::*;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let response = fetch("https://api.github.com/users/octocat", None).await?;
     
    if response.ok() {
        let user: serde_json::Value = response.json().await?;
        println!("User: {}", user["name"]);
    }
     
    Ok(())
}

§POST Request with JSON

use fetchttp::*;
use serde_json::json;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let data = json!({
        "name": "John Doe",
        "email": "john@example.com"
    });
     
    let mut init = RequestInit::new();
    init.method = Some("POST".to_string());
    init.body = Some(ReadableStream::from_json(&data));
     
    let response = fetch("https://api.example.com/users", Some(init)).await?;
     
    if response.ok() {
        println!("User created successfully!");
    }
     
    Ok(())
}

§Custom Headers

use fetchttp::*;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut headers = Headers::new();
    headers.set("Authorization", "Bearer your-token")?;
    headers.set("User-Agent", "MyApp/1.0")?;
     
    let mut init = RequestInit::new();
    init.headers = Some(headers);
     
    let response = fetch("https://api.example.com/protected", Some(init)).await?;
    let text = response.text().await?;
     
    println!("Response: {}", text);
    Ok(())
}

§API Overview

The main entry point is the fetch function, which takes a URL and optional RequestInit configuration. The function returns a Response that can be consumed in various ways:

§Error Handling

The library uses a comprehensive error system with specific error types:

All errors implement the standard Rust error traits.

Structs§

AbortController
A controller for managing abort signals.
AbortError
An abort error indicating the operation was cancelled.
AbortSignal
A signal that can be used to cancel operations.
Bytes
A cheaply cloneable and sliceable chunk of contiguous memory.
Headers
HTTP headers container following the WHATWG Fetch specification.
JsonMap
Represents a JSON key/value type.
NetworkError
A network error indicating connection or protocol failures.
ReadableStream
A readable stream representing request or response body data.
Request
An HTTP request following the WHATWG Fetch specification.
RequestInit
Configuration for creating requests.
Response
An HTTP response following the WHATWG Fetch specification.
ResponseInit
Configuration for creating responses.
TypeError
A type error indicating invalid arguments or operations.

Enums§

FetchError
The main error type for fetch operations.
JsonValue
Represents any valid JSON value.
RequestCache
Cache mode for requests.
RequestCredentials
Credentials mode for requests.
RequestMode
CORS mode for requests.
RequestRedirect
Redirect mode for requests.
ResponseType
Response type classification.

Functions§

fetch
Perform an HTTP request using the Fetch API.

Type Aliases§

Result
Convenient Result type alias for fetch operations.