newsapi 0.7.0

Wrapper for the newsapi, uses reqwest to do the http work. A learn by doing project
Documentation
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
use super::constants;
use super::error::NewsApiError;
use chrono::prelude::*;
use serde::de::DeserializeOwned;
use std::collections::HashMap;

use percent_encoding::{utf8_percent_encode, NON_ALPHANUMERIC};

#[derive(Debug)]
pub struct NewsAPIClient {
    api_key: String,
    parameters: HashMap<String, String>,
    url: Option<String>,
}

impl NewsAPIClient {
    /// Returns a NewsAPI with given api key
    ///
    /// # Arguments
    ///
    /// * `api_key` - a string that holds the api, this will be used to set X-Api-Key.
    ///
    pub fn new(api_key: String) -> NewsAPIClient {
        NewsAPIClient {
            api_key,
            parameters: HashMap::new(),
            url: None,
        }
    }

    /// Build the 'fetch everything' url
    pub fn everything(&mut self) -> &mut NewsAPIClient {
        let allowed_params = vec![
            "q",
            "sources",
            "domains",
            "excludeDomains",
            "from",
            "to",
            "language",
            "sortBy",
            "pageSize",
            "page",
        ];

        self.url = Some(self.build_url(constants::EVERYTHING_URL, allowed_params));
        self
    }

    /// Build the 'top_headlines' url
    pub fn top_headlines(&mut self) -> &mut NewsAPIClient {
        let allowed_params = vec!["q", "country", "category", "sources", "pageSize", "page"];
        self.url = Some(self.build_url(constants::TOP_HEADLINES_URL, allowed_params));
        self
    }

    /// Build the 'sources' url
    pub fn sources(&mut self) -> &mut NewsAPIClient {
        let allowed_params = vec!["category", "language", "country"];
        self.url = Some(self.build_url(constants::SOURCES_URL, allowed_params));
        self
    }

    /// Send the constructed URL to the newsapi server
    pub async fn send_async<T>(&self) -> Result<T, NewsApiError>
    where
        T: DeserializeOwned,
    {
        if self.invalid_arguments_specified() {
            return Err(NewsApiError::InvalidParameterCombinationError);
        }

        match &self.url {
            Some(url) => {
                let body = NewsAPIClient::fetch_resource_async(url, &self.api_key).await?;
                Ok(serde_json::from_str::<T>(&body)?)
            }
            None => Err(NewsApiError::UndefinedUrlError),
        }
    }

    /// Send the constructed URL to the newsapi server
    pub fn send_sync<T>(&self) -> Result<T, NewsApiError>
    where
        T: DeserializeOwned,
    {
        if self.invalid_arguments_specified() {
            return Err(NewsApiError::InvalidParameterCombinationError);
        }

        match &self.url {
            Some(url) => {
                let body = NewsAPIClient::fetch_resource_sync(url, &self.api_key)?;
                Ok(serde_json::from_str::<T>(&body)?)
            }
            None => Err(NewsApiError::UndefinedUrlError),
        }
    }

    fn build_url(&self, base_url: &str, allowed_params: Vec<&str>) -> String {
        let mut params: Vec<String> = vec![];
        for field in allowed_params {
            if let Some(value) = self.parameters.get(field) {
                params.push(format!("{field}={value}"))
            }
        }

        let mut url = base_url.to_owned();

        if params.is_empty() {
            url
        } else {
            url.push('?');
            url.push_str(&params.join("&"));
            url
        }
    }

    fn invalid_arguments_specified(&self) -> bool {
        (self.parameters.contains_key("country") || self.parameters.contains_key("category"))
            && self.parameters.contains_key("sources")
    }

    fn handle_api_error(error_code: u16, error_string: String) -> NewsApiError {
        match error_code {
            400 => NewsApiError::BadRequest {
                code: error_code,
                message: error_string,
            },
            401 => NewsApiError::Unauthorized {
                code: error_code,
                message: error_string,
            },
            429 => NewsApiError::TooManyRequests {
                code: error_code,
                message: error_string,
            },
            500 => NewsApiError::ServerError {
                code: error_code,
                message: error_string,
            },
            _ => NewsApiError::GenericError {
                code: error_code,
                message: error_string,
            },
        }
    }

    fn create_user_agent() -> String {
        concat!(
            "rust-",
            env!("CARGO_PKG_NAME"),
            "/",
            env!("CARGO_PKG_VERSION"),
        )
        .to_owned()
    }

    async fn fetch_resource_async(url: &str, api_key: &str) -> Result<String, NewsApiError> {
        // TODO: create a client that can be reused
        let client = reqwest::Client::builder()
            .user_agent(NewsAPIClient::create_user_agent())
            .build()?;

        let resp = client.get(url).header("X-Api-Key", api_key).send().await?;

        if resp.status().is_success() {
            Ok(resp.text().await?)
        } else {
            Err(NewsAPIClient::handle_api_error(
                resp.status().as_u16(),
                resp.text().await?,
            ))
        }
    }

    fn fetch_resource_sync(url: &str, api_key: &str) -> Result<String, NewsApiError> {
        // TODO: create a client that can be reused
        let client = reqwest::blocking::Client::builder()
            .user_agent(NewsAPIClient::create_user_agent())
            .build()?;

        let resp = client.get(url).header("X-Api-Key", api_key).send()?;

        if resp.status().is_success() {
            Ok(resp.text()?)
        } else {
            Err(NewsAPIClient::handle_api_error(
                resp.status().as_u16(),
                resp.text()?,
            ))
        }
    }

    /// A date and optional time for the oldest article allowed
    pub fn from(&mut self, from: &DateTime<Utc>) -> &mut NewsAPIClient {
        self.chronological_specification("from", from);
        self
    }

    /// A date and optional time for the newest article allowed.
    pub fn to(&mut self, to: &DateTime<Utc>) -> &mut NewsAPIClient {
        self.chronological_specification("to", to);
        self
    }

    fn chronological_specification(
        &mut self,
        operation: &str,
        dt_val: &DateTime<Utc>,
    ) -> &mut NewsAPIClient {
        let dt_format = "%Y-%m-%dT%H:%M:%S";
        self.parameters
            .insert(operation.to_owned(), dt_val.format(dt_format).to_string());
        self
    }

    ///  The domains
    /// (e.g. bbc.co.uk, techcrunch.com, engadget.com) to which search will be restricted.
    pub fn domains(&mut self, domains: Vec<&str>) -> &mut NewsAPIClient {
        self.manage_domains("domains", domains);
        self
    }

    /// The domains
    /// (e.g. bbc.co.uk, techcrunch.com, engadget.com) from which no stories will be present in the
    /// results.
    pub fn exclude_domains(&mut self, domains: Vec<&str>) -> &mut NewsAPIClient {
        self.manage_domains("excludeDomains", domains);
        self
    }

    fn manage_domains(&mut self, operation: &str, domains: Vec<&str>) -> &mut NewsAPIClient {
        self.parameters
            .insert(operation.to_owned(), domains.join(","));
        self
    }

    /// Narrow search to specific country
    pub fn country(&mut self, country: constants::Country) -> &mut NewsAPIClient {
        self.parameters.insert(
            "country".to_owned(),
            constants::COUNTRY_LOOKUP[country].to_string(),
        );
        self
    }

    /// Defaults to all categories - see constants.rs
    pub fn category(&mut self, category: constants::Category) -> &mut NewsAPIClient {
        let fmtd_category = format!("{category:?}").to_lowercase();
        self.parameters.insert("category".to_owned(), fmtd_category);
        self
    }

    /// Use the /sources endpoint to locate these programmatically or look at the sources index.
    /// Note: you can't mix this param with the country or category params.
    /// This will be checked before calling the API but you can still get rekt!
    pub fn with_sources(&mut self, sources: String) -> &mut NewsAPIClient {
        self.parameters.insert("sources".to_owned(), sources);
        self
    }

    /// Keywords or phrases to search for.
    ///
    /// * Surround phrases with quotes (") for exact match.
    /// * Prepend words or phrases that must appear with a + symbol. Eg: +bitcoin
    /// * Prepend words that must not appear with a - symbol. Eg: -bitcoin
    /// * Alternatively you can use the AND / OR / NOT keywords, and optionally group these with parenthesis.
    ///   e.g.: crypto AND (ethereum OR litecoin) NOT bitcoin
    pub fn query(&mut self, query: &str) -> &mut NewsAPIClient {
        self.parameters.insert(
            "q".to_owned(),
            utf8_percent_encode(query, NON_ALPHANUMERIC).to_string(),
        );
        self
    }

    pub fn page(&mut self, page: u32) -> &mut NewsAPIClient {
        self.parameters.insert("page".to_owned(), page.to_string());
        self
    }

    pub fn page_size(&mut self, size: u32) -> &mut NewsAPIClient {
        if (1..=100).contains(&size) {
            self.parameters
                .insert("pageSize".to_owned(), size.to_string());
        }
        self
    }

    pub fn language(&mut self, language: constants::Language) -> &mut NewsAPIClient {
        self.parameters.insert(
            "language".to_owned(),
            constants::LANG_LOOKUP[language].to_string(),
        );
        self
    }

    pub fn sort_by(&mut self, sort_by: constants::SortMethod) -> &mut NewsAPIClient {
        self.parameters.insert(
            "sort_by".to_owned(),
            constants::SORT_METHOD_LOOKUP[sort_by].to_string(),
        );
        self
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn handle_api_error() {
        let bad_request = NewsAPIClient::handle_api_error(400, "BadRequest".into());
        assert_eq!(bad_request.to_string(), "BadRequest: 400 => BadRequest");

        let generic_error =
            NewsAPIClient::handle_api_error(418, "Hyper Text Coffee Pot Control Protocol".into());
        assert_eq!(
            generic_error.to_string(),
            "GenericError: 418 => Hyper Text Coffee Pot Control Protocol"
        );
    }

    #[test]
    fn query() {
        let mut api = NewsAPIClient::new("123".to_owned());
        api.query("Ali loves the hoff NOT Baywatch");
        let encoded_param = api.parameters.get("q");
        assert_eq!(
            encoded_param,
            Some(&"Ali%20loves%20the%20hoff%20NOT%20Baywatch".to_string())
        );
    }

    #[test]
    fn build_url() {
        let mut api = NewsAPIClient::new("123".to_owned());
        api.language(constants::Language::English);
        api.country(constants::Country::UnitedStatesofAmerica);
        let expected = "https://newsapi.org/v2/sources?language=en&country=us".to_owned();
        let allowed_params = vec!["category", "language", "country"];
        let url = api.build_url(constants::SOURCES_URL, allowed_params);
        assert_eq!(expected, url);
    }

    #[test]
    fn domains() {
        let mut api = NewsAPIClient::new("123".to_owned());

        assert_eq!(api.parameters.get("domains"), None);
        assert_eq!(api.parameters.get("excludeDomains"), None);

        api.domains(vec!["www.bbc.co.uk"]);

        api.exclude_domains(vec!["www.facebook.com", "www.brexitbart.com"]);

        assert_eq!(
            api.parameters.get("domains"),
            Some(&"www.bbc.co.uk".to_owned())
        );

        assert_eq!(
            api.parameters.get("excludeDomains"),
            Some(&"www.facebook.com,www.brexitbart.com".to_owned())
        );
    }

    #[test]
    fn category() {
        let mut api = NewsAPIClient::new("123".to_owned());
        assert_eq!(api.parameters.get("category"), None);
        api.category(constants::Category::Science);
        assert_eq!(api.parameters.get("category"), Some(&"science".to_owned()));
    }

    #[test]
    fn country() {
        let mut api = NewsAPIClient::new("123".to_owned());
        assert_eq!(api.parameters.get("country"), None);
        api.country(constants::Country::Germany);
        assert_eq!(api.parameters.get("country"), Some(&"de".to_owned()));
    }

    #[test]
    fn language() {
        let mut api = NewsAPIClient::new("123".to_owned());
        api.language(constants::Language::English);
        assert_eq!(api.parameters.get("language"), Some(&"en".to_owned()));
    }

    #[test]
    fn to_and_from() {
        let mut api = NewsAPIClient::new("123".to_owned());

        let from = Utc.with_ymd_and_hms(2019, 7, 8, 9, 10, 11).unwrap();
        let to = Utc.with_ymd_and_hms(2019, 7, 9, 9, 10, 11).unwrap();

        api.to(&to).from(&from);

        assert_eq!(
            api.parameters.get("from"),
            Some(&"2019-07-08T09:10:11".to_owned())
        );
        assert_eq!(
            api.parameters.get("to"),
            Some(&"2019-07-09T09:10:11".to_owned())
        );
    }

    #[test]
    fn new() {
        let api = NewsAPIClient::new("123".to_string());
        assert_eq!(api.api_key, "123".to_string());
    }

    #[test]
    fn page() {
        let mut api = NewsAPIClient::new("123".to_owned());
        api.page(20);
        assert_eq!(api.parameters.get("page"), Some(&"20".to_owned()));
    }

    #[test]
    fn page_size() {
        let mut api = NewsAPIClient::new("123".to_owned());
        assert_eq!(api.parameters.get("pageSize"), None);
        api.page_size(30);
        assert_eq!(api.parameters.get("pageSize"), Some(&"30".to_owned()));
        api.page_size(400);
        assert_eq!(api.parameters.get("pageSize"), Some(&"30".to_owned()));
    }
}