pexels-api 0.1.0

A Rust client for the Pexels API. API Address: https://www.pexels.com/api/documentation/
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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
use reqwest::{header, Client, StatusCode};
use std::time::Duration;
use url::Url;

use crate::models::{CollectionsPage, MediaPage, Photo, PhotosPage, Video, VideosPage};
use crate::search::{
    CollectionMediaParams, PaginationParams, PopularVideoParams, SearchParams, VideoSearchParams,
};
use crate::PexelsError;

/// Main client for the Pexels API
///
/// This client provides methods to interact with all endpoints of the Pexels API
/// and handles authentication, request building and response parsing.
pub struct PexelsClient {
    /// API key for authentication with Pexels API
    api_key: String,

    /// HTTP client with connection pooling and configurable timeouts
    client: Client,

    /// Base URL for the Pexels API
    base_url: String,
}

impl PexelsClient {
    /// Creates a new PexelsClient with the provided API key
    ///
    /// # Arguments
    ///
    /// * `api_key` - The Pexels API key
    ///
    /// # Returns
    ///
    /// A new instance of PexelsClient
    ///
    /// # Example
    ///
    /// ```
    /// use pexels_api::PexelsClient;
    ///
    /// let client = PexelsClient::new("your_api_key");
    /// ```
    pub fn new<S: Into<String>>(api_key: S) -> Self {
        let client = Client::builder()
            .timeout(Duration::from_secs(30))
            .pool_max_idle_per_host(10)
            .build()
            .unwrap_or_default();

        Self { api_key: api_key.into(), client, base_url: "https://api.pexels.com/v1".to_string() }
    }

    /// Creates a new PexelsClient with custom configuration
    ///
    /// # Arguments
    ///
    /// * `api_key` - The Pexels API key
    /// * `timeout` - Request timeout in seconds
    /// * `max_idle_connections` - Maximum number of idle connections per host
    ///
    /// # Returns
    ///
    /// A new instance of PexelsClient
    pub fn with_config<S: Into<String>>(
        api_key: S,
        timeout: u64,
        max_idle_connections: usize,
    ) -> Self {
        let client = Client::builder()
            .timeout(Duration::from_secs(timeout))
            .pool_max_idle_per_host(max_idle_connections)
            .build()
            .unwrap_or_default();

        Self { api_key: api_key.into(), client, base_url: "https://api.pexels.com/v1".to_string() }
    }

    /// Sets a custom base URL for the Pexels API
    ///
    /// # Arguments
    ///
    /// * `base_url` - The custom base URL
    ///
    /// # Returns
    ///
    /// Self for method chaining
    pub fn with_base_url<S: Into<String>>(mut self, base_url: S) -> Self {
        self.base_url = base_url.into();
        self
    }

    /// Search for photos matching the specified query and parameters
    ///
    /// # Arguments
    ///
    /// * `query` - The search query
    /// * `params` - Additional search parameters (pagination, filters, etc.)
    ///
    /// # Returns
    ///
    /// A Result containing the photos search response or an error
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use pexels_api::{PexelsClient, SearchParams,Size};
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = PexelsClient::new("your_api_key");
    ///     let params = SearchParams::new()
    ///         .page(1)
    ///         .per_page(15)
    ///         .size(Size::Large);
    ///
    ///     let photos = client.search_photos("nature", &params).await?;
    ///     println!("Found {} photos", photos.total_results);
    ///     Ok(())
    /// }
    /// ```
    pub async fn search_photos(
        &self,
        query: &str,
        params: &SearchParams,
    ) -> Result<PhotosPage, PexelsError> {
        let mut url = Url::parse(&format!("{}/search", self.base_url))?;

        // Add query parameter
        url.query_pairs_mut().append_pair("query", query);

        // Add all search parameters
        for (key, value) in params.to_query_params() {
            url.query_pairs_mut().append_pair(&key, &value);
        }

        let response = self.send_request(url).await?;

        match response.status() {
            StatusCode::OK => {
                let photos_page: PhotosPage = response.json().await?;
                Ok(photos_page)
            }
            StatusCode::UNAUTHORIZED => Err(PexelsError::AuthError("Invalid API key".to_string())),
            StatusCode::TOO_MANY_REQUESTS => Err(PexelsError::RateLimitError),
            status => {
                Err(PexelsError::ApiError(format!("Search photos failed with status: {status}")))
            }
        }
    }

    /// Fetch curated/featured photos
    ///
    /// # Arguments
    ///
    /// * `params` - Pagination parameters
    ///
    /// # Returns
    ///
    /// A Result containing the curated photos response or an error
    pub async fn curated_photos(
        &self,
        params: &PaginationParams,
    ) -> Result<PhotosPage, PexelsError> {
        let mut url = Url::parse(&format!("{}/curated", self.base_url))?;

        self.append_query_params(&mut url, params.to_query_params());

        let response = self.send_request(url).await?;

        match response.status() {
            StatusCode::OK => {
                let photos_page: PhotosPage = response.json().await?;
                Ok(photos_page)
            }
            StatusCode::UNAUTHORIZED => Err(PexelsError::AuthError("Invalid API key".to_string())),
            StatusCode::TOO_MANY_REQUESTS => Err(PexelsError::RateLimitError),
            status => {
                Err(PexelsError::ApiError(format!("Curated photos failed with status: {status}")))
            }
        }
    }

    /// Get a specific photo by its ID
    ///
    /// # Arguments
    ///
    /// * `id` - The photo ID
    ///
    /// # Returns
    ///
    /// A Result containing the photo or an error
    pub async fn get_photo(&self, id: u64) -> Result<Photo, PexelsError> {
        let url = Url::parse(&format!("{}/photos/{}", self.base_url, id))?;

        let response = self.send_request(url).await?;

        match response.status() {
            StatusCode::OK => {
                let photo: Photo = response.json().await?;
                Ok(photo)
            }
            StatusCode::NOT_FOUND => {
                Err(PexelsError::NotFound(format!("Photo with ID {id} not found")))
            }
            StatusCode::UNAUTHORIZED => Err(PexelsError::AuthError("Invalid API key".to_string())),
            StatusCode::TOO_MANY_REQUESTS => Err(PexelsError::RateLimitError),
            status => Err(PexelsError::ApiError(format!("Get photo failed with status: {status}"))),
        }
    }

    /// Search for videos matching the specified query and parameters
    ///
    /// # Arguments
    ///
    /// * `query` - The search query
    /// * `params` - Additional search parameters (pagination, filters, etc.)
    ///
    /// # Returns
    ///
    /// A Result containing the videos search response or an error
    pub async fn search_videos(
        &self,
        query: &str,
        params: &VideoSearchParams,
    ) -> Result<VideosPage, PexelsError> {
        let mut url = Url::parse(&format!("{}/videos/search", self.base_url))?;

        // Add query parameter
        url.query_pairs_mut().append_pair("query", query);

        self.append_query_params(&mut url, params.to_query_params());

        let response = self.send_request(url).await?;

        match response.status() {
            StatusCode::OK => {
                let videos_page: VideosPage = response.json().await?;
                Ok(videos_page)
            }
            StatusCode::UNAUTHORIZED => Err(PexelsError::AuthError("Invalid API key".to_string())),
            StatusCode::TOO_MANY_REQUESTS => Err(PexelsError::RateLimitError),
            status => {
                Err(PexelsError::ApiError(format!("Search videos failed with status: {status}")))
            }
        }
    }

    /// Fetch popular videos
    ///
    /// # Arguments
    ///
    /// * `params` - Pagination parameters
    ///
    /// # Returns
    ///
    /// A Result containing the popular videos response or an error
    pub async fn popular_videos(
        &self,
        params: &PaginationParams,
    ) -> Result<VideosPage, PexelsError> {
        let params = PopularVideoParams::from_pagination(params);
        self.popular_videos_with_params(&params).await
    }

    /// Fetch popular videos with documented filters.
    ///
    /// # Arguments
    ///
    /// * `params` - Pagination, size and duration filters
    ///
    /// # Returns
    ///
    /// A Result containing the popular videos response or an error
    pub async fn popular_videos_with_params(
        &self,
        params: &PopularVideoParams,
    ) -> Result<VideosPage, PexelsError> {
        let mut url = Url::parse(&format!("{}/videos/popular", self.base_url))?;

        self.append_query_params(&mut url, params.to_query_params());

        let response = self.send_request(url).await?;

        match response.status() {
            StatusCode::OK => {
                let videos_page: VideosPage = response.json().await?;
                Ok(videos_page)
            }
            StatusCode::UNAUTHORIZED => Err(PexelsError::AuthError("Invalid API key".to_string())),
            StatusCode::TOO_MANY_REQUESTS => Err(PexelsError::RateLimitError),
            status => {
                Err(PexelsError::ApiError(format!("Popular videos failed with status: {status}")))
            }
        }
    }

    /// Get a specific video by its ID
    ///
    /// # Arguments
    ///
    /// * `id` - The video ID
    ///
    /// # Returns
    ///
    /// A Result containing the video or an error
    pub async fn get_video(&self, id: u64) -> Result<Video, PexelsError> {
        let url = Url::parse(&format!("{}/videos/videos/{}", self.base_url, id))?;

        let response = self.send_request(url).await?;

        match response.status() {
            StatusCode::OK => {
                let video: Video = response.json().await?;
                Ok(video)
            }
            StatusCode::NOT_FOUND => {
                Err(PexelsError::NotFound(format!("Video with ID {id} not found")))
            }
            StatusCode::UNAUTHORIZED => Err(PexelsError::AuthError("Invalid API key".to_string())),
            StatusCode::TOO_MANY_REQUESTS => Err(PexelsError::RateLimitError),
            status => Err(PexelsError::ApiError(format!("Get video failed with status: {status}"))),
        }
    }

    /// Get collections list
    ///
    /// # Arguments
    ///
    /// * `params` - Pagination parameters
    ///
    /// # Returns
    ///
    /// A Result containing the collections response or an error
    pub async fn get_collections(
        &self,
        params: &PaginationParams,
    ) -> Result<CollectionsPage, PexelsError> {
        let mut url = Url::parse(&format!("{}/collections", self.base_url))?;

        self.append_query_params(&mut url, params.to_query_params());

        let response = self.send_request(url).await?;

        match response.status() {
            StatusCode::OK => {
                let collections_page: CollectionsPage = response.json().await?;
                Ok(collections_page)
            }
            StatusCode::UNAUTHORIZED => Err(PexelsError::AuthError("Invalid API key".to_string())),
            StatusCode::TOO_MANY_REQUESTS => Err(PexelsError::RateLimitError),
            status => {
                Err(PexelsError::ApiError(format!("Get collections failed with status: {status}")))
            }
        }
    }

    /// Get featured collections list
    ///
    /// # Arguments
    ///
    /// * `params` - Pagination parameters
    ///
    /// # Returns
    ///
    /// A Result containing the featured collections response or an error
    pub async fn get_featured_collections(
        &self,
        params: &PaginationParams,
    ) -> Result<CollectionsPage, PexelsError> {
        let mut url = Url::parse(&format!("{}/collections/featured", self.base_url))?;

        self.append_query_params(&mut url, params.to_query_params());

        let response = self.send_request(url).await?;

        match response.status() {
            StatusCode::OK => {
                let collections_page: CollectionsPage = response.json().await?;
                Ok(collections_page)
            }
            StatusCode::UNAUTHORIZED => Err(PexelsError::AuthError("Invalid API key".to_string())),
            StatusCode::TOO_MANY_REQUESTS => Err(PexelsError::RateLimitError),
            status => Err(PexelsError::ApiError(format!(
                "Get featured collections failed with status: {status}"
            ))),
        }
    }

    /// Get collection media items (photos and videos)
    ///
    /// # Arguments
    ///
    /// * `id` - The collection ID
    /// * `params` - Pagination parameters
    ///
    /// # Returns
    ///
    /// A Result containing the media response or an error
    pub async fn get_collection_media(
        &self,
        id: &str,
        params: &PaginationParams,
    ) -> Result<MediaPage, PexelsError> {
        let params = CollectionMediaParams::from_pagination(params);
        self.get_collection_media_with_params(id, &params).await
    }

    /// Get collection media items (photos and videos) with documented filters
    ///
    /// # Arguments
    ///
    /// * `id` - The collection ID
    /// * `params` - Pagination, media type and sort filters
    ///
    /// # Returns
    ///
    /// A Result containing the media response or an error
    pub async fn get_collection_media_with_params(
        &self,
        id: &str,
        params: &CollectionMediaParams,
    ) -> Result<MediaPage, PexelsError> {
        let mut url = Url::parse(&format!("{}/collections/{}", self.base_url, id))?;

        self.append_query_params(&mut url, params.to_query_params());

        let response = self.send_request(url).await?;

        match response.status() {
            StatusCode::OK => {
                let media_page: MediaPage = response.json().await?;
                Ok(media_page)
            }
            StatusCode::NOT_FOUND => {
                Err(PexelsError::NotFound(format!("Collection with ID {id} not found")))
            }
            StatusCode::UNAUTHORIZED => Err(PexelsError::AuthError("Invalid API key".to_string())),
            StatusCode::TOO_MANY_REQUESTS => Err(PexelsError::RateLimitError),
            status => Err(PexelsError::ApiError(format!(
                "Get collection media failed with status: {status}"
            ))),
        }
    }

    fn append_query_params(&self, url: &mut Url, params: Vec<(String, String)>) {
        for (key, value) in params {
            url.query_pairs_mut().append_pair(&key, &value);
        }
    }

    /// Helper method to send authenticated requests to the Pexels API
    ///
    /// # Arguments
    ///
    /// * `url` - The fully constructed URL to send the request to
    ///
    /// # Returns
    ///
    /// A Result containing the HTTP response or an error
    async fn send_request(&self, url: Url) -> Result<reqwest::Response, PexelsError> {
        let response =
            self.client.get(url).header(header::AUTHORIZATION, &self.api_key).send().await?;

        Ok(response)
    }
}