Trait api_forge::traits::Request

source ·
pub trait Request<Res>
where Self: Serialize + Debug,
{ type Response = Res; const ENDPOINT: &'static str; const METHOD: Method = reqwest::Method::GET; const DATA_TRANSMISSION_METHOD: DataTransmissionMethod = DataTransmissionMethod::QueryParams; const AUTHENTICATION_METHOD: AuthenticationMethod = AuthenticationMethod::None; // Required method async fn from_response( resp: Response, ) -> Result<Self::Response, ApiForgeError>; // Provided methods fn multipart_form_data(&self) -> Form { ... } fn generate_request( &self, base_url: &str, headers: Option<HeaderMap>, token: Option<(String, Option<String>)>, ) -> RequestBuilder { ... } async fn send_request( &self, base_url: &str, headers: Option<HeaderMap>, token: Option<(String, Option<String>)>, ) -> Result<Response> { ... } async fn send_and_parse( &self, base_url: &str, headers: Option<HeaderMap>, token: Option<(String, Option<String>)>, ) -> Result<Self::Response, ApiForgeError> { ... } }
Expand description

Request trait.

This trait defines a structure for making HTTP requests with custom serialization and response handling. It is intended to be implemented by request types that are serializable and can generate HTTP requests.

§Requirements

Implementing types must:

  • Implement the Serialize trait from serde for serializing the request data.
  • Implement the Debug trait for debugging purposes.
  • Define a constant ENDPOINT representing the API endpoint.

§Associated Constants

  • ENDPOINT: A static string representing the endpoint for the request.
  • METHOD: The HTTP method (default is GET).
  • DATA_TRANSMISSION_METHOD: Specifies how the request data is sent (default is QueryParams).
  • AUTHENTICATION_METHOD: Specifies the authentication method (default is None).

§Methods

  • generate_request: Generates a reqwest::RequestBuilder based on the request type.
  • send_request: Sends the request asynchronously and returns the response.
  • send_and_parse: Sends the request and parses the response, returning a result or an error.

§Example

use serde::{Serialize, Deserialize};
use reqwest::header::HeaderMap;
use reqwest::Method;
use api_forge::{Request, DataTransmissionMethod, AuthenticationMethod, ApiForgeError};

#[derive(Serialize, Debug)]
struct MyRequest {
    field1: String,
    field2: i32,
}

#[derive(Deserialize, Debug, Default)]
struct MyResponse {
    result: String,
}

impl From<reqwest::Response> for MyResponse {
    fn from(resp: reqwest::Response) -> Self {
        // Convert the response into your response structure
        resp.json().unwrap_or_else(|_| MyResponse {
            result: "Error parsing response".into(),
        })
    }
}

impl Request<MyResponse> for MyRequest {
    const ENDPOINT: &'static str = "/api/my_endpoint";
    const METHOD: Method = Method::POST; // Override HTTP method if necessary
    const DATA_TRANSMISSION_METHOD: DataTransmissionMethod = DataTransmissionMethod::Json; // Send data as JSON
    const AUTHENTICATION_METHOD: AuthenticationMethod = AuthenticationMethod::Bearer; // Use Bearer authentication
    async fn from_response(resp: reqwest::Response) -> Result<Self::Response, ApiForgeError> where <Self as Request<MyResponse>>::Response: From<reqwest::Response> {
        resp.json().await
    }
}

#[tokio::main]
async fn main() {
    let request = MyRequest {
        field1: "Test".to_string(),
        field2: 42,
    };

    let headers = HeaderMap::new();
    let token = Some(("my_token".to_string(), None));

    match request.send_and_parse("https://api.example.com", Some(headers), token).await {
        Ok(response) => println!("Success: {:?}", response),
        Err(e) => eprintln!("Request failed: {:?}", e),
    }
}

Required Associated Constants§

source

const ENDPOINT: &'static str

A static string representing the endpoint for the request.

Provided Associated Constants§

source

const METHOD: Method = reqwest::Method::GET

Determines the HTTP method for the request. Defaults to GET.

source

const DATA_TRANSMISSION_METHOD: DataTransmissionMethod = DataTransmissionMethod::QueryParams

Specifies how the data will be transmitted in the request. The default is DataTransmissionMethod::QueryParams.

source

const AUTHENTICATION_METHOD: AuthenticationMethod = AuthenticationMethod::None

Specifies the method of authentication for the request. The default is AuthenticationMethod::None.

Provided Associated Types§

source

type Response = Res

The type of the response, which must implement From<reqwest::Response>.

Required Methods§

Provided Methods§

source

fn multipart_form_data(&self) -> Form

Optional: Provides multipart form data for file uploads.

source

fn generate_request( &self, base_url: &str, headers: Option<HeaderMap>, token: Option<(String, Option<String>)>, ) -> RequestBuilder

Generates a reqwest::RequestBuilder based on the request’s parameters, including optional headers and authentication.

source

async fn send_request( &self, base_url: &str, headers: Option<HeaderMap>, token: Option<(String, Option<String>)>, ) -> Result<Response>

Sends the request asynchronously and returns the result.

source

async fn send_and_parse( &self, base_url: &str, headers: Option<HeaderMap>, token: Option<(String, Option<String>)>, ) -> Result<Self::Response, ApiForgeError>

Sends the request and attempts to parse the response. Returns a Result containing the parsed response or an error.

Examples found in repository?
examples/json_placeholder.rs (line 34)
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
async fn main() {
    // Initialize the request.
    let request = GetPosts;

    // Define the base URL (e.g., JSONPlaceholder API for testing).
    let base_url = "https://jsonplaceholder.typicode.com";

    // Send the request and await the response.
    let result = request.send_and_parse(base_url, None, None).await;

    match result {
        Ok(post) => println!("Successfully fetched post: {:?}", post),
        Err(e) => eprintln!("Error occurred: {:?}", e),
    }
}

Object Safety§

This trait is not object safe.

Implementors§