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 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
#![doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/README.md"))]
use futures_util::{future::ready, TryFutureExt};
pub use reqwest::Error;
use reqwest::{Client, RequestBuilder, Response, Result};
use serde::{de::DeserializeOwned, Serialize};
/// Before one can do any api request, an ApiClient must be constructed
pub struct ApiClient {
client: Client,
prefix: String,
authentication: Authentication,
}
pub struct ApiClientBuilder {
prefix: String,
authentication: Authentication,
user_agent: Option<String>,
}
impl ApiClientBuilder {
pub fn new(prefix: &str) -> Self {
Self {
prefix: prefix.to_owned(),
authentication: Authentication::default(),
user_agent: None,
}
}
pub fn authentication(&mut self, auth: Authentication) -> &mut Self {
self.authentication = auth;
self
}
pub fn user_agent(&mut self, user_agent: &str) -> &mut Self {
self.user_agent = Some(user_agent.to_owned());
self
}
pub fn build(&self) -> Result<ApiClient> {
Client::builder()
.user_agent(
self.user_agent
.clone()
.unwrap_or("Rest Api Client".to_owned()),
)
.build()
.map(|client| ApiClient {
authentication: self.authentication.clone(),
client,
prefix: self.prefix.clone(),
})
}
}
/// This library support two ways of authentication
/// Either Basic of Bearer
#[derive(Clone, Default)]
pub enum Authentication {
Basic(BasicAuthentication),
Bearer(String),
#[default]
None,
}
impl Authentication {
pub fn new_basic(username: &str, password: &str) -> Self {
Authentication::Basic(BasicAuthentication::new(username, password))
}
pub fn new_bearer(token: &str) -> Self {
Authentication::Bearer(token.to_owned())
}
}
#[derive(Clone)]
pub struct BasicAuthentication {
username: String,
password: String,
}
impl BasicAuthentication {
/// Create a new instance of BasicAuthentication with provided username and password
pub fn new(username: &str, password: &str) -> Self {
Self {
username: username.into(),
password: password.into(),
}
}
}
impl ApiClient {
fn create_request<T>(
&self,
uri: &str,
f: impl Fn(&Client, String) -> RequestBuilder,
t: Option<T>,
) -> RequestBuilder
where
T: Serialize,
{
let mut builder = f(&self.client, self.uri(uri));
builder = match &self.authentication {
Authentication::Basic(basic) => {
builder.basic_auth(basic.username.clone(), Some(basic.password.clone()))
}
Authentication::Bearer(token) => builder.bearer_auth(token),
Authentication::None => builder,
};
if let Some(object) = t {
builder = builder.json(&object)
}
builder
}
fn uri(&self, uri: &str) -> String {
format!("{}{}", self.prefix, uri)
}
/// # Example
///
/// Try to delete a post with specific id from [Json Placeholder](https://jsonplaceholder.typicode.com/)
///
/// ```
/// # use rest_json_client::{ApiClientBuilder, Authentication, Error};
/// # use json_placeholder_dataposts::Post;
/// #
/// # tokio_test::block_on(async {
/// let base = "https://jsonplaceholder.typicode.com/";
/// ApiClientBuilder::new(base)
/// .build()?
/// .delete("posts/1")
/// .await?;
///
/// # Ok::<(), Error>(())
/// # });
/// ```
pub async fn delete(&self, uri: &str) -> Result<()> {
self.create_request::<()>(uri, Client::delete, None)
.send()
.and_then(|r| ready(r.error_for_status()).map_ok(|_| ()))
.await
}
/// # Example 1
///
/// Try to return a list of posts from [JsonPlaceholder](https://jsonplaceholder.typicode.com/)
///
/// ```rust
/// # use rest_json_client::{ApiClientBuilder, Authentication, Error};
/// # use json_placeholder_dataposts::Post;
/// #
/// # tokio_test::block_on(async {
/// let base = "https://jsonplaceholder.typicode.com/";
/// let posts = ApiClientBuilder::new(base)
/// .build()?
/// .get::<Vec<Post>>("posts")
/// .await?;
///
/// # assert_eq!(posts.len(), 100);
/// # Ok::<(), Error>(())
/// # });
/// ```
///
/// # Example 2
///
/// Try to return a single post with specific id from [Json Placeholder](https://jsonplaceholder.typicode.com/)
///
/// ```rust
/// # use rest_json_client::{ApiClientBuilder, Authentication, Error};
/// # use json_placeholder_dataposts::Post;
/// #
/// # tokio_test::block_on(async {
/// let base = "https://jsonplaceholder.typicode.com/";
/// let post = ApiClientBuilder::new(base)
/// .build()?
/// .get::<Post>("posts/1")
/// .await?;
///
/// # assert_eq!(post.user_id, Some(1));
/// # Ok::<(), Error>(())
/// # });
/// ```
pub async fn get<R>(&self, uri: &str) -> Result<R>
where
R: DeserializeOwned,
{
self.create_request::<()>(uri, Client::get, None)
.send()
.and_then(Response::json::<R>)
.await
}
/// # Example
///
/// Try to create a new post on [Json Placeholder](https://jsonplaceholder.typicode.com/)
/// If successful the created post is returned
///
/// ```
/// # use rest_json_client::{ApiClientBuilder, Authentication, Error};
/// # use json_placeholder_dataposts::Post;
/// #
/// # tokio_test::block_on(async {
///
/// let new_post = Post {
/// id: None,
/// title: "Hallo".to_owned(),
/// body: "Hallo".to_owned(),
/// user_id: Some(34),
/// };
/// let base = "https://jsonplaceholder.typicode.com/";
/// let post = ApiClientBuilder::new(base)
/// .build()?
/// .post::<_, Post>("posts", new_post)
/// .await?;
///
/// # assert_eq!(post.user_id, Some(34));
/// # Ok::<(), Error>(())
/// # });
/// ```
pub async fn post<T, R>(&self, uri: &str, object: T) -> Result<R>
where
T: Serialize,
R: DeserializeOwned,
{
self.create_request::<T>(uri, Client::post, Some(object))
.send()
.and_then(Response::json::<R>)
.await
}
/// # Example
///
/// Try to change a post with specific id on [Json Placeholder](https://jsonplaceholder.typicode.com/)
/// If successful the changed post is returned
///
/// ```
/// # use rest_json_client::{ApiClientBuilder, Authentication, Error};
/// # use json_placeholder_dataposts::Post;
/// #
/// # tokio_test::block_on(async {
///
/// let changed_post = Post {
/// id: None,
/// title: "Hallo".to_owned(),
/// body: "Hallo".to_owned(),
/// user_id: Some(34),
/// };
/// let base = "https://jsonplaceholder.typicode.com/";
/// let post = ApiClientBuilder::new(base)
/// .build()?
/// .put::<_, Post>("posts/1", changed_post)
/// .await?;
///
/// # assert_eq!(post.user_id, Some(34));
/// # Ok::<(), Error>(())
/// # });
/// ```
pub async fn put<T, R>(&self, uri: &str, object: T) -> Result<R>
where
T: Serialize,
R: DeserializeOwned,
{
self.create_request::<T>(uri, Client::put, Some(object))
.send()
.and_then(Response::json::<R>)
.await
}
}