pub trait Request<Res>{
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
Serializetrait fromserdefor serializing the request data. - Implement the
Debugtrait for debugging purposes. - Define a constant
ENDPOINTrepresenting the API endpoint.
§Associated Constants
ENDPOINT: A static string representing the endpoint for the request.METHOD: The HTTP method (default isGET).DATA_TRANSMISSION_METHOD: Specifies how the request data is sent (default isQueryParams).AUTHENTICATION_METHOD: Specifies the authentication method (default isNone).
§Methods
generate_request: Generates areqwest::RequestBuilderbased 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§
Provided Associated Constants§
sourceconst METHOD: Method = reqwest::Method::GET
const METHOD: Method = reqwest::Method::GET
Determines the HTTP method for the request. Defaults to GET.
sourceconst DATA_TRANSMISSION_METHOD: DataTransmissionMethod = DataTransmissionMethod::QueryParams
const DATA_TRANSMISSION_METHOD: DataTransmissionMethod = DataTransmissionMethod::QueryParams
Specifies how the data will be transmitted in the request.
The default is DataTransmissionMethod::QueryParams.
sourceconst AUTHENTICATION_METHOD: AuthenticationMethod = AuthenticationMethod::None
const AUTHENTICATION_METHOD: AuthenticationMethod = AuthenticationMethod::None
Specifies the method of authentication for the request.
The default is AuthenticationMethod::None.
Provided Associated Types§
Required Methods§
async fn from_response(resp: Response) -> Result<Self::Response, ApiForgeError>
Provided Methods§
sourcefn multipart_form_data(&self) -> Form
fn multipart_form_data(&self) -> Form
Optional: Provides multipart form data for file uploads.
sourcefn generate_request(
&self,
base_url: &str,
headers: Option<HeaderMap>,
token: Option<(String, Option<String>)>,
) -> RequestBuilder
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.
sourceasync fn send_request(
&self,
base_url: &str,
headers: Option<HeaderMap>,
token: Option<(String, Option<String>)>,
) -> Result<Response>
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.
sourceasync fn send_and_parse(
&self,
base_url: &str,
headers: Option<HeaderMap>,
token: Option<(String, Option<String>)>,
) -> Result<Self::Response, ApiForgeError>
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?
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),
}
}