google-search-console-api 0.2.0

Unofficial Rust client for Google Search Console API
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
//! # Google Search Console API Client
//!
//! An unofficial Rust client library for the Google Search Console API.
//!
//! ## Features
//!
//! - **Search Analytics** - Query search performance data
//! - **Sitemaps** - Manage sitemaps
//! - **Sites** - Manage sites
//! - **URL Inspection** - Inspect URLs for indexing status
//! - **Mobile Friendly Test** - Test mobile friendliness
//!
//! ## Example
//!
//! ```rust,no_run
//! use google_search_console_api::SearchConsoleApi;
//! use google_search_console_api::search_analytics::query::SearchAnalyticsQueryRequest;
//! use google_search_console_api::types::Dimension;
//!
//! #[tokio::main]
//! async fn main() {
//!     let token = "your_oauth_token";
//!     let site_url = "https://example.com/";
//!
//!     let request = SearchAnalyticsQueryRequest::builder("2024-01-01", "2024-01-31")
//!         .dimensions(vec![Dimension::Query, Dimension::Page])
//!         .row_limit(100)
//!         .build();
//!
//!     let response = SearchConsoleApi::search_analytics()
//!         .query(token, site_url, request)
//!         .await;
//! }
//! ```

mod error;
mod http;

pub mod mobile_friendly_test;
pub mod search_analytics;
pub mod sitemaps;
pub mod sites;
pub mod types;
pub mod url_inspection;

use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use urlencoding::encode;

pub use error::*;

use crate::http::HttpClient;
use crate::mobile_friendly_test::{RequestMobileFriendlyTest, ResponseMobileFriendlyTest};
use crate::search_analytics::query::{SearchAnalyticsQueryRequest, SearchAnalyticsQueryResponse};
use crate::sitemaps::ResponseSitemapApiList;
use crate::sites::{ResponseSiteApi, ResponseSiteListApi};
use crate::url_inspection::{RequestUrlInspection, ResponseInspectionResult};

/// Main entry point for the Google Search Console API.
///
/// Provides access to all API endpoints through method chaining.
///
/// # Example
///
/// ```rust,no_run
/// use google_search_console_api::SearchConsoleApi;
///
/// # async fn example() {
/// let sites = SearchConsoleApi::sites().list("token").await;
/// # }
/// ```
pub struct SearchConsoleApi;

impl SearchConsoleApi {
    /// Access the Search Analytics API.
    ///
    /// Query search performance data including clicks, impressions, CTR, and position.
    pub fn search_analytics() -> SearchAnalyticsApi {
        SearchAnalyticsApi
    }

    /// Access the Sitemaps API.
    ///
    /// List, submit, and delete sitemaps for your sites.
    pub fn sitemaps() -> SitemapsApi {
        SitemapsApi
    }

    /// Access the Sites API.
    ///
    /// Add, remove, and list sites in your Search Console account.
    pub fn sites() -> SitesApi {
        SitesApi
    }

    /// Access the URL Inspection API.
    ///
    /// Inspect URLs for indexing status, crawl info, and more.
    pub fn url_inspection() -> UrlInspectionApi {
        UrlInspectionApi
    }

    /// Access the Mobile Friendly Test API.
    ///
    /// Test whether a page is mobile-friendly.
    pub fn mobile_friendly_test() -> MobileFriendlyTestApi {
        MobileFriendlyTestApi
    }
}

/// Search Analytics API client.
///
/// Query search traffic data for your site.
///
/// # API Reference
///
/// <https://developers.google.com/webmaster-tools/v1/searchanalytics>
#[derive(Default)]
pub struct SearchAnalyticsApi;

impl SearchAnalyticsApi {
    /// Query search analytics data.
    ///
    /// # Arguments
    ///
    /// * `token` - OAuth2 access token
    /// * `url` - Site URL (e.g., `https://example.com/`)
    /// * `request` - Query parameters
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use google_search_console_api::SearchConsoleApi;
    /// use google_search_console_api::search_analytics::query::SearchAnalyticsQueryRequest;
    ///
    /// # async fn example() {
    /// let request = SearchAnalyticsQueryRequest::builder("2024-01-01", "2024-01-31")
    ///     .row_limit(100)
    ///     .build();
    ///
    /// let response = SearchConsoleApi::search_analytics()
    ///     .query("token", "https://example.com/", request)
    ///     .await;
    /// # }
    /// ```
    pub async fn query(
        &self,
        token: &str,
        url: &str,
        request: SearchAnalyticsQueryRequest,
    ) -> Result<SearchAnalyticsQueryResponse, GoogleApiError> {
        HttpClient::post(
            token,
            &format!(
                "https://www.googleapis.com/webmasters/v3/sites/{}/searchAnalytics/query",
                encode(url)
            ),
            request,
        )
        .await
    }
}

#[derive(Default, Debug, Serialize, Deserialize, Clone)]
pub(crate) struct DummyRequest {}

/// Sitemaps API client.
///
/// Manage sitemaps for your sites.
///
/// # API Reference
///
/// <https://developers.google.com/webmaster-tools/v1/sitemaps>
#[derive(Default)]
pub struct SitemapsApi;

impl SitemapsApi {
    /// Delete a sitemap.
    ///
    /// # Arguments
    ///
    /// * `token` - OAuth2 access token
    /// * `site_url` - Site URL
    /// * `feed_path` - Full URL of the sitemap to delete
    pub async fn delete(
        &self,
        token: &str,
        site_url: &str,
        feed_path: &str,
    ) -> Result<Value, GoogleApiError> {
        HttpClient::delete(
            token,
            &format!(
                "https://www.googleapis.com/webmasters/v3/sites/{}/sitemaps/{}",
                encode(site_url),
                encode(feed_path)
            ),
            json!({}),
        )
        .await
    }

    /// Get information about a specific sitemap.
    ///
    /// # Arguments
    ///
    /// * `token` - OAuth2 access token
    /// * `site_url` - Site URL
    /// * `feed` - Full URL of the sitemap
    pub async fn get(
        &self,
        token: &str,
        site_url: &str,
        feed: &str,
    ) -> Result<Value, GoogleApiError> {
        HttpClient::get(
            token,
            &format!(
                "https://www.googleapis.com/webmasters/v3/sites/{}/sitemaps/{}",
                encode(site_url),
                encode(feed)
            ),
            json!({}),
        )
        .await
    }

    /// List all sitemaps for a site.
    ///
    /// # Arguments
    ///
    /// * `token` - OAuth2 access token
    /// * `site_url` - Site URL
    pub async fn list(
        &self,
        token: &str,
        site_url: &str,
    ) -> Result<ResponseSitemapApiList, GoogleApiError> {
        HttpClient::get(
            token,
            &format!(
                "https://www.googleapis.com/webmasters/v3/sites/{}/sitemaps",
                encode(site_url)
            ),
            DummyRequest::default(),
        )
        .await
    }

    /// Resubmit a sitemap.
    ///
    /// # Arguments
    ///
    /// * `token` - OAuth2 access token
    /// * `site_url` - Site URL
    /// * `feed` - Full URL of the sitemap
    pub async fn put(
        &self,
        token: &str,
        site_url: &str,
        feed: &str,
    ) -> Result<Value, GoogleApiError> {
        HttpClient::post(
            token,
            &format!(
                "https://www.googleapis.com/webmasters/v3/sites/{}/sitemaps/{}",
                encode(site_url),
                encode(feed)
            ),
            json!({}),
        )
        .await
    }

    /// Submit a new sitemap.
    ///
    /// # Arguments
    ///
    /// * `token` - OAuth2 access token
    /// * `site_url` - Site URL
    /// * `feed` - Full URL of the sitemap to submit
    pub async fn submit(
        &self,
        token: &str,
        site_url: &str,
        feed: &str,
    ) -> Result<Value, GoogleApiError> {
        HttpClient::put(
            token,
            &format!(
                "https://www.googleapis.com/webmasters/v3/sites/{}/sitemaps/{}",
                encode(site_url),
                encode(feed)
            ),
            json!({}),
        )
        .await
    }
}

/// Sites API client.
///
/// Manage sites in your Search Console account.
///
/// # API Reference
///
/// <https://developers.google.com/webmaster-tools/v1/sites>
#[derive(Default)]
pub struct SitesApi;

impl SitesApi {
    /// Add a site to Search Console.
    ///
    /// # Arguments
    ///
    /// * `token` - OAuth2 access token
    /// * `site_url` - URL of the site to add
    pub async fn add(&self, token: &str, site_url: &str) -> Result<Value, GoogleApiError> {
        HttpClient::put(
            token,
            &format!(
                "https://www.googleapis.com/webmasters/v3/sites/{}",
                encode(site_url)
            ),
            DummyRequest::default(),
        )
        .await
    }

    /// Remove a site from Search Console.
    ///
    /// # Arguments
    ///
    /// * `token` - OAuth2 access token
    /// * `site_url` - URL of the site to remove
    pub async fn delete(&self, token: &str, site_url: &str) -> Result<Value, GoogleApiError> {
        HttpClient::delete(
            token,
            &format!(
                "https://www.googleapis.com/webmasters/v3/sites/{}",
                encode(site_url)
            ),
            DummyRequest::default(),
        )
        .await
    }

    /// Get information about a specific site.
    ///
    /// # Arguments
    ///
    /// * `token` - OAuth2 access token
    /// * `site_url` - URL of the site
    pub async fn get(
        &self,
        token: &str,
        site_url: &str,
    ) -> Result<ResponseSiteApi, GoogleApiError> {
        HttpClient::get(
            token,
            &format!(
                "https://www.googleapis.com/webmasters/v3/sites/{}",
                encode(site_url)
            ),
            DummyRequest::default(),
        )
        .await
    }

    /// List all sites in your Search Console account.
    ///
    /// # Arguments
    ///
    /// * `token` - OAuth2 access token
    pub async fn list(&self, token: &str) -> Result<ResponseSiteListApi, GoogleApiError> {
        HttpClient::get(
            token,
            "https://www.googleapis.com/webmasters/v3/sites",
            DummyRequest::default(),
        )
        .await
    }
}

/// URL Inspection API client.
///
/// Inspect URLs for indexing status and other information.
///
/// # API Reference
///
/// <https://developers.google.com/webmaster-tools/v1/urlInspection.index>
#[derive(Default)]
pub struct UrlInspectionApi;

impl UrlInspectionApi {
    /// Inspect a URL.
    ///
    /// Returns indexing status, crawl info, AMP status, mobile usability, and rich results.
    ///
    /// # Arguments
    ///
    /// * `token` - OAuth2 access token
    /// * `request` - Inspection request parameters
    pub async fn inspect(
        &self,
        token: &str,
        request: &RequestUrlInspection,
    ) -> Result<ResponseInspectionResult, GoogleApiError> {
        HttpClient::post(
            token,
            "https://searchconsole.googleapis.com/v1/urlInspection/index:inspect",
            request,
        )
        .await
    }
}

/// Mobile Friendly Test API client.
///
/// Test whether a page is mobile-friendly.
///
/// # API Reference
///
/// <https://developers.google.com/webmaster-tools/v1/urlTestingTools.mobileFriendlyTest>
#[derive(Default)]
pub struct MobileFriendlyTestApi;

impl MobileFriendlyTestApi {
    /// Run a mobile-friendly test.
    ///
    /// Note: This API uses an API key instead of OAuth2.
    ///
    /// # Arguments
    ///
    /// * `api_key` - Google API key
    /// * `request` - Test request parameters
    pub async fn run(
        &self,
        api_key: &str,
        request: &RequestMobileFriendlyTest,
    ) -> Result<ResponseMobileFriendlyTest, GoogleApiError> {
        HttpClient::post(
            "",
            &format!(
                "https://searchconsole.googleapis.com/v1/urlTestingTools/mobileFriendlyTest:run?key={}",
                api_key
            ),
            request,
        )
        .await
    }
}