-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparams.rs
More file actions
103 lines (90 loc) · 2.36 KB
/
params.rs
File metadata and controls
103 lines (90 loc) · 2.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
//! Example demonstrating path parameters and query parameters.
//!
//! This example shows how to use `path_params` for dynamic URL segments
//! and `query_params` for query string parameters.
use http_provider_macro::api_client;
use reqwest::Url;
use serde::{Deserialize, Serialize};
// Response types
#[derive(Deserialize, Debug)]
#[allow(dead_code)]
struct User {
id: u32,
name: String,
email: String,
}
#[derive(Deserialize, Debug)]
#[allow(dead_code)]
struct SearchResults {
results: Vec<User>,
total: u32,
}
// Path parameters - fields must match the `{param}` placeholders in the path
#[derive(Serialize)]
struct UserPathParams {
id: u32,
}
#[derive(Serialize)]
struct PostPathParams {
post_id: u32,
}
// Query parameters - will be serialized as query string
#[derive(Serialize)]
struct SearchQueryParams {
q: String,
limit: Option<u32>,
offset: Option<u32>,
}
// Define an API client with path and query parameters
api_client!(
ApiClient,
{
{
path: "/users/{id}",
method: GET,
path_params: UserPathParams,
res: User,
},
{
path: "/posts/{post_id}",
method: GET,
path_params: PostPathParams,
res: Post,
},
{
path: "/search",
method: GET,
query_params: SearchQueryParams,
res: SearchResults,
},
}
);
#[derive(Deserialize, Debug)]
#[allow(dead_code)]
struct Post {
id: u32,
title: String,
content: String,
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let base_url = Url::parse("https://api.example.com")?;
let client = ApiClient::new(base_url, Some(5000));
// Use path parameters - the `{id}` in the path will be replaced with the value
let user = client.get_users_by_id(&UserPathParams { id: 42 }).await?;
println!("User: {:?}", user);
let post = client
.get_posts_by_post_id(&PostPathParams { post_id: 1 })
.await?;
println!("Post: {:?}", post);
// Use query parameters - will be serialized as ?q=rust&limit=10
let results = client
.get_search(&SearchQueryParams {
q: "rust".to_string(),
limit: Some(10),
offset: Some(0),
})
.await?;
println!("Search results: {:?}", results);
Ok(())
}