derive/
derive.rs

1use std::collections::HashMap;
2
3use api_forge::ApiRequest;
4use api_forge_macro::Request;
5use serde::{Deserialize, Serialize};
6
7#[derive(Serialize, Deserialize, Debug, Clone, Request)]
8#[request(endpoint = "/posts", response_type = Posts)]
9pub struct GetPosts;
10
11#[derive(Serialize, Deserialize, Debug, Clone, Default)]
12pub struct Post {
13    #[serde(rename = "userId")]
14    pub user_id: i32,
15    pub id: i32,
16    pub title: String,
17    pub body: String,
18}
19
20#[derive(Serialize, Deserialize, Debug, Clone, Default, Request)]
21#[request(endpoint = "/posts", response_type = Post, method = POST, transmission = Json)]
22pub struct CreatePost {
23    #[serde(rename = "userId")]
24    pub user_id: i32,
25    pub title: String,
26    pub body: String,
27
28    #[request(header_name = "test")]
29    #[serde(skip)]
30    header: Option<String>,
31}
32
33#[derive(Serialize, Deserialize, Debug, Clone, Default, Request)]
34#[request(endpoint = "/posts/{id}", response_type = EmptyResponse, method = DELETE, path_parameters = ["id"])]
35pub struct DeletePost {
36    pub id: i32,
37}
38
39#[derive(Serialize, Deserialize, Debug, Clone, Default)]
40pub struct Posts(Vec<Post>);
41
42#[derive(Serialize, Deserialize, Debug, Clone, Default)]
43pub struct EmptyResponse(HashMap<String, String>);
44
45#[tokio::main]
46async fn main() {
47    // Initialize the request.
48    let request = GetPosts;
49
50    // Define the base URL (e.g., JSONPlaceholder API for testing).
51    let base_url = "https://jsonplaceholder.typicode.com";
52
53    // Send the request and await the response.
54    let result = request.send_and_parse(base_url, None, None).await;
55
56    match result {
57        Ok(post) => println!("Successfully fetched post: {:?}", post),
58        Err(e) => eprintln!("Error occurred: {:?}", e),
59    }
60
61    // Initialize the request.
62    let request = CreatePost {
63        user_id: 1,
64        title: "Test".to_string(),
65        body: "Test".to_string(),
66        header: Some("test-header".to_string()),
67    };
68
69    // Send the request and await the response.
70    let result = request.send_and_parse(base_url, None, None).await;
71
72    match result {
73        Ok(post) => println!("Successfully created post: {:?}", post),
74        Err(e) => eprintln!("Error occurred: {:?}", e),
75    }
76
77    // Initialize the request.
78    let request = DeletePost { id: 100 };
79
80    // Send the request and await the response.
81    let result = request.send_and_parse(base_url, None, None).await;
82
83    match result {
84        Ok(post) => println!("Successfully deleted post: {:?}", post),
85        Err(e) => eprintln!("Error occurred: {:?}", e),
86    }
87}