Skip to content

uiuifree/rust-google-indexing-api

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

10 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Rust Google Indexing API

Crates.io Documentation License Downloads

A Rust library for interfacing with the Google Indexing API. Notify Google when pages are added, updated, or deleted on your website for faster indexing in search results.

Features

  • URL Notifications: Notify Google about URL updates and deletions
  • Metadata Retrieval: Fetch metadata about indexed URLs from Google
  • Batch Operations: Process multiple URLs efficiently in a single request (up to 100 URLs)
  • Async/Await Support: Built with Tokio for modern async Rust applications
  • Type-Safe API: Leverages Rust's type system for safer API interactions
  • Error Handling: Comprehensive error types for robust applications

Prerequisites

Before using this library, you need to:

  1. Enable the Google Indexing API in your Google Cloud Console
  2. Create a Service Account and download the JSON key file
  3. Grant permissions to the service account in Google Search Console for your property

For detailed setup instructions, see the Google Indexing API documentation.

Installation

Add this to your Cargo.toml:

[dependencies]
google-indexing-api = "1.0"
tokio = { version = "1", features = ["full"] }
yup-oauth2 = "12" # For authentication

Quick Start

Basic Example with Authentication

use google_indexing_api::{GoogleIndexingApi, UrlNotificationsType};
use yup_oauth2::ServiceAccountAuthenticator;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Load service account credentials
    let secret = yup_oauth2::read_service_account_key("service-account-key.json")
        .await
        .expect("Failed to read service account key");

    // Create authenticator
    let auth = ServiceAccountAuthenticator::builder(secret)
        .build()
        .await?;

    // Get access token
    let scopes = &["https://www.googleapis.com/auth/indexing"];
    let token = auth.token(scopes).await?;
    let token_str = token.token().unwrap();

    // Initialize API client
    let api = GoogleIndexingApi::url_notifications();

    // Notify Google about a URL update
    let response = api.publish(
        token_str,
        "https://example.com/page1",
        UrlNotificationsType::UPDATED
    ).await?;

    println!("Successfully notified Google about the URL update");
    Ok(())
}

Single URL Operations

use google_indexing_api::{GoogleIndexingApi, UrlNotificationsType};

let api = GoogleIndexingApi::url_notifications();

// Notify about an updated URL
let response = api.publish(
    token_str,
    "https://example.com/new-article",
    UrlNotificationsType::UPDATED
).await?;

// Notify about a deleted URL
let response = api.publish(
    token_str,
    "https://example.com/old-article",
    UrlNotificationsType::DELETED
).await?;

// Get metadata about a URL
let metadata = api.get_metadata(
    token_str,
    "https://example.com/article"
).await?;

Batch Operations

Process up to 100 URLs in a single request for better performance:

use google_indexing_api::{GoogleIndexingApi, UrlNotificationsType};

let api = GoogleIndexingApi::url_notifications();

let urls = vec![
    "https://example.com/page1".to_string(),
    "https://example.com/page2".to_string(),
    "https://example.com/page3".to_string(),
];

let batch_response = api.batch(
    token_str,
    urls,
    UrlNotificationsType::UPDATED
).await?;

// Process batch results
for result in batch_response {
    println!("URL: {}", result.url());
    println!("Status Code: {}", result.status_code);
    if let Some(json) = result.json() {
        println!("Response: {:?}", json);
    }
}

API Reference

GoogleIndexingApi::url_notifications()

Creates a new API client for URL notifications.

Methods

publish(token: &str, url: &str, notification_type: UrlNotificationsType) -> Result<T, GoogleApiError>

Notify Google about a single URL update or deletion.

Parameters:

  • token: OAuth2 access token
  • url: The URL to notify Google about
  • notification_type: Either UrlNotificationsType::UPDATED or UrlNotificationsType::DELETED

get_metadata(token: &str, url: &str) -> Result<T, GoogleApiError>

Retrieve metadata about a URL from Google's index.

Parameters:

  • token: OAuth2 access token
  • url: The URL to get metadata for

batch(token: &str, urls: Vec<String>, notification_type: UrlNotificationsType) -> Result<Vec<ResponseGoogleIndexingBatch>, GoogleApiError>

Notify Google about multiple URLs in a single batch request.

Parameters:

  • token: OAuth2 access token
  • urls: Vector of URLs (up to 100)
  • notification_type: Either UrlNotificationsType::UPDATED or UrlNotificationsType::DELETED

URL Notification Types

pub enum UrlNotificationsType {
    UPDATED,  // Notify that a URL has been updated or added
    DELETED,  // Notify that a URL has been deleted
}

Error Handling

The library provides comprehensive error handling through the GoogleApiError enum:

use google_indexing_api::GoogleApiError;

match api.publish(token_str, url, UrlNotificationsType::UPDATED).await {
    Ok(response) => println!("Success: {:?}", response),
    Err(GoogleApiError::Connection(e)) => eprintln!("Connection error: {}", e),
    Err(GoogleApiError::JsonParse(e)) => eprintln!("JSON parse error: {}", e),
    Err(e) => eprintln!("Other error: {:?}", e),
}

Rate Limits

The Google Indexing API has the following quotas:

  • 200 requests per day (default quota)
  • Request quota increase through Google Cloud Console if needed

For batch operations, each URL in the batch counts toward your quota.

Examples

See the tests directory for more complete examples including:

  • Service account authentication
  • Batch processing
  • Error handling patterns

Requirements

  • Rust 1.70 or later
  • Tokio runtime for async operations

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Links

About

This is a Rust library for interfacing with the Google Indexing API

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages