Skip to main content

newsapi_rust/
client.rs

1//! The main client for interacting with NewsAPI.
2
3use std::time::Duration;
4
5use reqwest::Client as HttpClient;
6
7pub use crate::{
8    error::{NewsApiError, Result},
9    models::{ApiResponse, SourceDetail, SourcesResponse, SuccessResponse},
10    params::{EverythingParams, SourceParams, TopHeadlinesParams},
11    version::ApiVersion,
12};
13
14const BASE_URL: &str = "https://newsapi.org";
15
16/// The main NewsAPI client.
17///
18/// Holds your API key, HTTP client configuration, and provides methods for all API endpoints.
19/// All methods are asynchronous and must be `await`ed.
20///
21/// # Examples
22/// ```no_run
23/// use newsapi_rust::{NewsApiClient, TopHeadlinesParams};
24///
25/// #[tokio::main]
26/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
27///     let client = NewsApiClient::new("YOUR_API_KEY");
28///     let params = TopHeadlinesParams::new().country("us").category("technology");
29///     let headlines = client.top_headlines(&params).await?;
30///     for article in headlines.articles {
31///         println!("{} - {}", article.title, article.url);
32///     }
33///     Ok(())
34/// }
35#[derive(Debug, Clone)]
36pub struct NewsApiClient {
37    api_key: String,
38    timeout: Duration,
39    http: HttpClient,
40    version: ApiVersion,
41}
42
43impl NewsApiClient {
44    /// Create a new NewsApiClient with the given API key.
45    ///
46    /// Uses default settings for timeout (30 seconds) and API version (v2).
47    pub fn new(api_key: impl Into<String>) -> Self {
48        Self::with_config(api_key, Duration::from_secs(30), ApiVersion::default())
49    }
50
51    /// Create a new NewsApiClient with custom configuration.
52    pub fn with_config(api_key: impl Into<String>, timeout: Duration, version: ApiVersion) -> Self {
53        let http = HttpClient::builder()
54            .timeout(timeout)
55            .build()
56            .expect("Failed to build HTTP client");
57
58        Self {
59            http,
60            api_key: api_key.into(),
61            version,
62            timeout,
63        }
64    }
65
66    /// Create a new NewsApiClient with a custom timeout.
67    pub fn with_timeout(api_key: impl Into<String>, timeout: Duration) -> Self {
68        Self::with_config(api_key, timeout, ApiVersion::V2)
69    }
70
71    /// Create a new NewsApiClient with a specific API version.
72    pub fn with_version(api_key: impl Into<String>, version: ApiVersion) -> Self {
73        Self::with_config(api_key, Duration::from_secs(30), version)
74    }
75
76    /// Set the API version for this client.
77    pub fn set_version(&mut self, version: ApiVersion) {
78        self.version = version;
79    }
80
81    /// Get the current API version.
82    pub fn version(&self) -> ApiVersion {
83        self.version
84    }
85
86    /// Set the timeout for HTTP requests. Rebuilds the internal HTTP client with the new timeout.
87    pub fn set_timeout(&mut self, timeout: Duration) -> Result<()> {
88        let new_http = HttpClient::builder()
89            .timeout(timeout)
90            .build()
91            .map_err(|e| NewsApiError::Request(e.into()))?;
92        self.http = new_http;
93        self.timeout = timeout;
94        Ok(())
95    }
96
97    // Helper method to build the full URL for a given endpoint
98    fn build_url(&self, endpoint: &str) -> String {
99        format!("{}{}/{}", BASE_URL, self.version.path(), endpoint)
100    }
101
102    // Helper method to execute a request with error handling
103    async fn execute_request(
104        &self,
105        request: reqwest::RequestBuilder,
106        timeout: Option<Duration>,
107    ) -> Result<reqwest::Response> {
108        let request = if let Some(t) = timeout {
109            request.timeout(t)
110        } else {
111            request
112        };
113        request.send().await.map_err(|e| {
114            if e.is_timeout() {
115                let actual_timeout = timeout.unwrap_or(self.timeout);
116                NewsApiError::Timeout(actual_timeout)
117            } else {
118                NewsApiError::Request(e)
119            }
120        })
121    }
122
123    // Helper method to handle API responses and convert them into SuccessResponse or NewsApiError
124    async fn handle_response(&self, response: reqwest::Response) -> Result<SuccessResponse> {
125        let body = response.bytes().await?;
126        let api_response: ApiResponse = serde_json::from_slice(&body)?;
127        match api_response {
128            ApiResponse::Success(success) => Ok(success),
129            ApiResponse::Error(error) => {
130                if error.code == "rateLimited" {
131                    Err(NewsApiError::RateLimitExceeded)
132                } else if error.code == "apiKeyInvalid" {
133                    Err(NewsApiError::InvalidApiKey)
134                } else {
135                    Err(NewsApiError::Api {
136                        code: error.code,
137                        message: error.message,
138                    })
139                }
140            }
141            ApiResponse::Unknown => Err(NewsApiError::InvalidParams(
142                "Unexpected response format".into(),
143            )),
144        }
145    }
146
147    /// Fetch top headlines using `/top-headlines` endpoint with the given parameters.
148    ///
149    /// # Arguments
150    /// * `params` - A reference to `TopHeadlinesParams` containing the query parameters.
151    ///
152    /// # Returns
153    /// A `Result` containing `SuccessResponse` on success or `NewsApiError` on failure.
154    pub async fn top_headlines(&self, params: &TopHeadlinesParams) -> Result<SuccessResponse> {
155        self.top_headlines_with_timeout(params, None).await
156    }
157
158    /// Fetch top headlines using `/top-headlines` endpoint with the given parameters and an optional timeout.
159    ///
160    /// # Arguments
161    /// * `params` - A reference to `TopHeadlinesParams` containing the query parameters.
162    /// * `timeout` - An optional `Duration` specifying the timeout for the request.
163    ///
164    /// # Returns
165    /// A `Result` containing `SuccessResponse` on success or `NewsApiError` on failure.
166    pub async fn top_headlines_with_timeout(
167        &self,
168        params: &TopHeadlinesParams,
169        timeout: Option<Duration>,
170    ) -> Result<SuccessResponse> {
171        let mut query = vec![("apiKey", self.api_key.to_string())];
172
173        if let Some(country) = &params.country {
174            query.push(("country", country.to_string()));
175        }
176
177        if let Some(category) = &params.category {
178            query.push(("category", category.to_string()));
179        }
180
181        if let Some(sources) = &params.sources {
182            query.push(("sources", sources.to_string()));
183        }
184
185        if let Some(q) = &params.q {
186            query.push(("q", q.to_string()));
187        }
188
189        if let Some(page) = params.page {
190            query.push(("page", page.to_string()));
191        }
192
193        if let Some(page_size) = params.page_size {
194            query.push(("pageSize", page_size.to_string()));
195        }
196
197        let url = self.build_url("/top-headlines");
198        let request = self.http.get(&url).query(&query);
199        let response = self.execute_request(request, timeout).await?;
200        self.handle_response(response).await
201    }
202
203    /// Fetch all articles using the `/everything` endpoint with the given parameters.
204    ///
205    /// # Arguments
206    /// * `params` - A reference to `EverythingParams` containing the query parameters.
207    ///
208    /// # Returns
209    /// A `Result` containing `SuccessResponse` on success or `NewsApiError` on failure.
210    pub async fn everything(&self, params: &EverythingParams) -> Result<SuccessResponse> {
211        self.everything_with_timeout(params, None).await
212    }
213
214    /// Fetch all articles using the `/everything` endpoint with the given parameters and an optional timeout.
215    ///
216    /// # Arguments
217    /// * `params` - A reference to `EverythingParams` containing the query parameters.
218    /// * `timeout` - An optional `Duration` specifying the timeout for the request.
219    ///
220    /// # Returns
221    /// A `Result` containing `SuccessResponse` on success or `NewsApiError` on failure.
222    pub async fn everything_with_timeout(
223        &self,
224        params: &EverythingParams,
225        timeout: Option<Duration>,
226    ) -> Result<SuccessResponse> {
227        let mut query = vec![("apiKey", self.api_key.to_string())];
228        if let Some(q) = &params.q {
229            query.push(("q", q.to_string()));
230        }
231
232        if let Some(q_in_title) = &params.q_in_title {
233            query.push(("qInTitle", q_in_title.to_string()));
234        }
235
236        if let Some(sources) = &params.sources {
237            query.push(("sources", sources.to_string()));
238        }
239
240        if let Some(domains) = &params.domains {
241            query.push(("domains", domains.to_string()));
242        }
243
244        if let Some(from) = &params.from {
245            query.push(("from", from.to_string()));
246        }
247
248        if let Some(to) = &params.to {
249            query.push(("to", to.to_string()));
250        }
251
252        if let Some(language) = &params.language {
253            query.push(("language", language.to_string()));
254        }
255
256        if let Some(sort_by) = &params.sort_by {
257            query.push(("sortBy", sort_by.to_string()));
258        }
259
260        if let Some(page) = params.page {
261            query.push(("page", page.to_string()));
262        }
263
264        if let Some(page_size) = params.page_size {
265            query.push(("pageSize", page_size.to_string()));
266        }
267
268        let url = self.build_url("/everything");
269        let request = self.http.get(&url).query(&query);
270        let response = self.execute_request(request, timeout).await?;
271        self.handle_response(response).await
272    }
273
274    /// Fetch news sources using the `/sources` endpoint with the given parameters.
275    ///
276    /// # Arguments
277    /// * `params` - A reference to `SourceParams` containing the query parameters.
278    ///
279    /// # Returns
280    /// A `Result` containing a vector of `SourceDetail` on success or `NewsApiError` on failure.
281    pub async fn sources(&self, params: &SourceParams) -> Result<Vec<SourceDetail>> {
282        self.sources_with_timeout(params, None).await
283    }
284
285    /// Fetch news sources using the `/sources` endpoint with the given parameters and an optional timeout.
286    ///
287    /// # Arguments
288    /// * `params` - A reference to `SourceParams` containing the query parameters.
289    /// * `timeout` - An optional `Duration` specifying the timeout for the request.
290    ///
291    /// # Returns
292    /// A `Result` containing a vector of `SourceDetail` on success or `NewsApiError` on failure.
293    pub async fn sources_with_timeout(
294        &self,
295        params: &SourceParams,
296        timeout: Option<Duration>,
297    ) -> Result<Vec<SourceDetail>> {
298        let mut query = vec![("apiKey", self.api_key.to_string())];
299
300        if let Some(category) = &params.category {
301            query.push(("category", category.to_string()));
302        }
303
304        if let Some(language) = &params.language {
305            query.push(("language", language.to_string()));
306        }
307
308        if let Some(country) = &params.country {
309            query.push(("country", country.to_string()));
310        }
311
312        let url = self.build_url("/sources");
313        let request = self.http.get(&url).query(&query);
314        let response = self.execute_request(request, timeout).await?;
315        let body = response.bytes().await?;
316
317        let source_resp: SourcesResponse = serde_json::from_slice(&body)?;
318        match source_resp {
319            SourcesResponse::Ok { sources } => Ok(sources),
320            SourcesResponse::Err(err) => Err(NewsApiError::Api {
321                code: err.code,
322                message: err.message,
323            }),
324            SourcesResponse::Unknown => Err(NewsApiError::InvalidParams(
325                "Unknown response from sources endpoint".into(),
326            )),
327        }
328    }
329}