#endpoint #rest #api

restep

简单而实用的REST API端点生成器

3个版本 (破坏性)

0.3.0 2022年8月16日
0.2.0 2022年8月16日
0.1.0 2022年8月15日

#1498 in 进程宏

自定义许可

11KB
134

Crates.io Docs.rs

restep

Restep可以创建高度可读的APIClient。

用法

自动生成返回指定端点的 endpoint() 函数。

基本

use restep::endpoint;

#[endpoint("/customers")]
fn simple() -> String {
    // You can use `fn endpoint() -> String` in this function.
    endpoint()
}
assert_eq!(simple(), "/customers");

路径参数

use restep::endpoint;

struct PathParameters {
    customer_id: i32,
}

#[endpoint("/customers/{customer_id}", params = "PathParameters")]
fn dynamic_route() -> String {
    let params = PathParameters { customer_id: 1 };
    // You can use `fn endpoint(params: &PathParameters) -> String` in this function.
    endpoint(&params)
}
assert_eq!(dynamic_route(), "/customers/1");

实现

use restep::endpoint;

struct APIClient;

// Also You can change the function name.
#[endpoint("/customers", name = "__endpoint")]
impl APIClient {
    pub fn path() -> String {
        Self::__endpoint()
    }
}

assert_eq!(APIClient::path(), "/customers");

示例

现实世界

use restep::endpoint;

#[derive(serde::Deserialize)]
struct Customer {
    id: i32,
    name: String,
}

struct APIClient {
    client: reqwest::Client,
}

struct PathParameters {
    customer_id: i32,
}

impl APIClient {
    #[endpoint("/customer/{customer_id}", params = "PathParameters")]
    async fn get_customer(&self, params: PathParameters) -> anyhow::Result<Customer> {
        let url = format!("{}{}", std::env::var("BASE_URL").unwrap(), endpoint(&params));
        let customer = self.client
            .get(url)
            .send()
            .await?
            .json()
            .await?;
        Ok(customer)
    }
}

依赖关系

~2MB
~42K SLoC