7 releases

new 0.3.3 Oct 8, 2024
0.3.2 Oct 4, 2024
0.2.0 Apr 9, 2024
0.1.1 Apr 4, 2024

#141 in HTTP client

Download history 17/week @ 2024-06-20 73/week @ 2024-06-27 47/week @ 2024-07-04 25/week @ 2024-07-11 26/week @ 2024-07-18 2/week @ 2024-07-25 16/week @ 2024-08-01 15/week @ 2024-08-08 34/week @ 2024-08-15 81/week @ 2024-08-22 41/week @ 2024-08-29 53/week @ 2024-09-05 118/week @ 2024-09-12 52/week @ 2024-09-19 142/week @ 2024-09-26 482/week @ 2024-10-03

802 downloads per month

MIT/Apache

22KB
518 lines

reqwest-enum

crates.io CI

Type-safe and enum style API for Rust, some benefits:

  1. It abstracts away repetitive boilerplate code like url formatting, query / header encoding and response deserialization.
  2. Type-safe endpoints, readable like a spec, easy to add new or refactor existing endpoints.
  3. Async by default and lightweight JSON-RPC support.

Features:

  • Type-safe and enum style HTTP API
  • JSON-RPC with batching support
  • ...

Installation

cargo add reqwest-enum or add it to your Cargo.toml:

[dependencies]
reqwest-enum = "0.3.2"

Example

httpbin.org

  1. Define endpoints for https://httbin.org as an enum:
pub enum HttpBin {
    Get,
    Post,
    Bearer,
}
  1. Implement Target for the enum:
pub trait Target {
    fn base_url(&self) -> &'static str;
    fn method(&self) -> HTTPMethod;
    fn path(&self) -> String;
    fn query(&self) -> HashMap<&'static str, &'static str>;
    fn headers(&self) -> HashMap<&'static str, &'static str>;
    fn authentication(&self) -> Option<AuthMethod>;
    fn body(&self) -> HTTPBody;
    fn timeout(&self) -> Option<Duration>;
}
  1. Create a provider and request:
let provider = Provider::<HttpBin>::default();
let response = provider.request(HttpBin::Get).await.unwrap();
assert_eq!(response.status(), 200);

Provider also allows you to customize the request by providing a EndpointFn or RequestBuilderFn closure if default behavior is not sufficient:

  1. Need to use different endpoint based on the target.
  2. Need to insert custom headers or intercept the final request.

JSON-RPC

Full example can be found in examples/ethereum-rpc.

  1. Define Ethereum JSON-RPC methods as an enum:
pub enum EthereumRPC {
    ChainId,
    GasPrice,
    BlockNumber,
    GetBalance(&'static str),
    GetBlockByNumber(&'static str, bool),
    GetTransactionCount(&'static str, BlockParameter),
    Call(TransactionObject, BlockParameter),
    EstimateGas(TransactionObject),
    SendRawTransaction(&'static str),
}
  1. Implement Target and JsonRpcTarger for the enum:
pub trait JsonRpcTarget: Target {
    fn method_name(&self) -> &'static str;
    fn params(&self) -> Vec<Value>;
}
  1. Create a provider and request:
let provider = Provider::<EthereumRPC>::default();
let response: JsonRpcResponse<String> =
    provider.request_json(EthereumRPC::ChainId).await.unwrap();
assert_eq!(response.result, "0x1");

License

MIT or Apache-2.0

Credits

Dependencies

~4–14MB
~197K SLoC