An open API service indexing awesome lists of open source software.

https://github.com/pardel/rust-sdk-vonage

Rust SDK for Vonage APIs (unofficial)
https://github.com/pardel/rust-sdk-vonage

Last synced: 4 months ago
JSON representation

Rust SDK for Vonage APIs (unofficial)

Awesome Lists containing this project

README

          

# Rust SDK for Vonage APIs

[![Build Status](https://github.com/pardel/rust-sdk-vonage/workflows/CI/badge.svg)](https://github.com/pardel/rust-sdk-vonage/actions)
[![Crate](https://img.shields.io/crates/v/vonage.svg)](https://crates.io/crates/vonage)
[![API](https://docs.rs/vonage/badge.svg)](https://docs.rs/vonage)

This SDK provides a Rust interface to the [Vonage APIs](https://www.vonage.com/).

## Features

- **SMS API**: Send and receive SMS messages
- **Authentication**: Support for API Key/Secret and Signature authentication
- **Async Support**: Built with async/await from the ground up
- **Regional Support**: Support for different API regions (US, EU, AP)
- **Type Safety**: Comprehensive error handling and type-safe API
- **Modular Design**: Use individual crates or the unified SDK

## Quick Start

Add this to your `Cargo.toml`:

```toml
[dependencies]
vonage = "0.1.1"
tokio = { version = "1.0", features = ["full"] }
```

### Send an SMS (Legacy SMS API)

```rust
use vonage::{Vonage, BasicAuth};
use vonage::sms::SmsRequest;

#[tokio::main]
async fn main() -> Result<(), Box> {
// Create a client with your API credentials
let vonage = Vonage::new(BasicAuth::new(
std::env::var("VONAGE_API_KEY")?,
std::env::var("VONAGE_API_SECRET")?,
))?;

// Send an SMS message
let request = SmsRequest::text("Vonage", "15551234567", "Hello from Vonage!")
.with_client_ref("my-message-001")
.with_status_report(true);

let response = vonage.sms().send(&request).await?;

println!("Sent {} messages", response.message_count);

// Check if all messages were successful
if response.all_successful() {
println!("All messages sent successfully!");
for message in &response.messages {
println!("Message ID: {}", message.message_id);
}
} else {
println!("Some messages failed:");
for failed in response.failed_messages() {
println!("Failed to send to {}: {} - {}",
failed.to,
failed.status.description(),
failed.error_text.as_deref().unwrap_or("No error text")
);
}
}

Ok(())
}
```

### Send an SMS with Signature Authentication

For enhanced security, you can use signature authentication with the SMS API:

```rust
use vonage::{Vonage, SignatureAuth};
use vonage::sms::SmsRequest;

#[tokio::main]
async fn main() -> Result<(), Box> {
// Create a client with signature authentication
let vonage = Vonage::new(SignatureAuth::new(
std::env::var("VONAGE_API_KEY")?,
std::env::var("SMS_SIGNATURE")?, // Your SMS signature secret
))?;

// Send an SMS message (same API as basic auth)
let request = SmsRequest::text("Vonage", "15551234567", "Hello with signature auth!");
let response = vonage.sms().send(&request).await?;

println!("Sent {} messages", response.message_count);
Ok(())
}
```

### Convenience Method

For simple text messages, you can use the convenience method:

```rust
use vonage::{Vonage, BasicAuth};

#[tokio::main]
async fn main() -> Result<(), Box> {
let vonage = Vonage::new(BasicAuth::new("api_key", "api_secret"))?;

let response = vonage.sms().send_text("Vonage", "15551234567", "Hello!").await?;
println!("Message sent: {}", response.messages[0].message_id);

Ok(())
}
```

You can customize the client configuration:

```rust
use vonage::{Vonage, BasicAuth, Region};
use std::time::Duration;

#[tokio::main]
async fn main() -> Result<(), Box> {
let vonage = Vonage::builder()
.region(Region::EuWest) // Use EU region
.timeout(Duration::from_secs(60)) // 60 second timeout
.user_agent("MyApp/1.0.0") // Custom user agent
.max_retries(5) // Retry failed requests
.debug(true) // Enable debug logging
.build(BasicAuth::new("api_key", "api_secret"))?;

// Use the configured client
let response = vonage.sms().send_text("Vonage", "15551234567", "Hello!").await?;

Ok(())
}
```

### Debug Logging

Enable debug logging to see detailed HTTP request and response information:

```rust
let vonage = Vonage::builder()
.debug(true) // Shows HTTP traffic
.build(BasicAuth::new("api_key", "api_secret"))?;
```

This will output:

- HTTP method and URL
- Request headers (auth headers redacted for security)
- Request body (pretty-printed JSON)
- Response status and headers
- Response body (raw JSON)

### Configuration

### Advanced SMS Options

```rust
use vonage::{Vonage, BasicAuth};
use vonage::sms::{SmsRequest, MessageClass};

#[tokio::main]
async fn main() -> Result<(), Box> {
let vonage = Vonage::new(BasicAuth::new("api_key", "api_secret"))?;

let request = SmsRequest::text("Vonage", "15551234567", "Hello World!")
.with_client_ref("my-ref-001") // Your reference
.with_callback("https://example.com/webhooks") // Delivery receipt URL
.with_status_report(true) // Request delivery receipts
.with_ttl(86400000); // 24 hour TTL

let response = vonage.sms().send(&request).await?;
println!("Sent {} messages", response.message_count);

Ok(())
}
```

## Running the Examples

The SDK includes example code that demonstrates how to use the various features. To run the examples:

1. Copy the environment template:

```bash
cp examples/.env.example examples/.env
```

2. Edit `examples/.env` with your actual Vonage API credentials:

```bash
# Get your credentials from https://dashboard.nexmo.com/
VONAGE_API_KEY=your_api_key_here
VONAGE_API_SECRET=your_api_secret_here

# Optional: Customize SMS sender and recipient (defaults shown)
FROM_NUMBER=Vonage
TO_NUMBER=15551234567
```

3. Run the examples:

### SMS Examples

From within the `code-snippets` folder:

```bash
cd code-snippets
```

one can run the SMS examples:

```bash
# SMS API example
cargo run --bin sms-send
```

### Example Features

**SMS Examples:**

- `sms-send`: Basic SMS sending
- `sms-send-unicode`: Unicode SMS with special characters
- `sms-send-signed-message`: SMS with signature authentication
- `sms-delivery-receipt`: Handle delivery receipt webhooks
- `sms-receive`: Handle inbound SMS webhooks
- `sms-verify-signed-message`: Verify SMS signature authentication

Each example includes detailed configuration instructions, error handling, and troubleshooting tips.

**Debug Mode**: All examples have debug logging enabled by default, which provides detailed HTTP request/response information to help with troubleshooting and development. Debug output will be shown in the console when running examples.

All examples use [dotenvy](https://docs.rs/dotenvy/latest/dotenvy/) to automatically load credentials from the `.env` file.

## Error Handling

The SDK provides comprehensive error handling:

```rust
use vonage::{Vonage, BasicAuth, VonageError};

#[tokio::main]
async fn main() -> Result<(), Box> {
let vonage = Vonage::new(BasicAuth::new("api_key", "api_secret"))?;

match vonage.sms().send_text("Vonage", "invalid", "Hello!").await {
Ok(response) => {
println!("Success: {} messages sent", response.message_count);
}
Err(VonageError::Auth(auth_err)) => {
println!("Authentication error: {}", auth_err);
}
Err(VonageError::Http(http_err)) => {
println!("HTTP error: {}", http_err);
}
Err(VonageError::Api { status, message }) => {
println!("API error {}: {}", status, message);
}
Err(VonageError::Config(config_err)) => {
println!("Configuration error: {}", config_err);
}
Err(err) => {
println!("Other error: {}", err);
}
}

Ok(())
}
```

## Modular Usage

You can use individual crates if you only need specific functionality:

```toml
[dependencies]
vonage-core = "0.1.0" # Core types, auth, and HTTP client
vonage-sms = "0.1.0" # SMS API
```

```rust
use vonage_sms::{SmsClient, SmsRequest};
use vonage_core::BasicAuth;

#[tokio::main]
async fn main() -> Result<(), Box> {
// Using the SMS API
let sms_client = SmsClient::new()?;
let auth = BasicAuth::new("api_key", "api_secret");
let request = SmsRequest::text("Vonage", "15551234567", "Hello!");

let response = sms_client.send(&auth, &request).await?;
println!("Sent {} messages", response.message_count);

Ok(())
}
```

## Supported APIs

| API | Status | Supported? |
|-----------------------|:-----------:|:----------:|
| Account API | Coming soon | ❌ |
| Alerts API | Coming soon | ❌ |
| Application API | Coming soon | ❌ |
| Audit API | Coming soon | ❌ |
| Conversation API | Coming soon | ❌ |
| Dispatch API | Coming soon | ❌ |
| External Accounts API | Coming soon | ❌ |
| Media API | Coming soon | ❌ |
| Messages API | Coming soon | ❌ |
| Meetings API | Coming soon | ❌ |
| Number Insight V2 API | Coming soon | ❌ |
| Number Insights API | Coming soon | ❌ |
| Number Management API | Coming soon | ❌ |
| Pricing API | Coming soon | ❌ |
| Redact API | Coming soon | ❌ |
| Reports API | Coming soon | ❌ |
| SMS API | Available | ✅ v1.2.1 |
| Sub Accounts | Coming soon | ❌ |
| Users | Coming soon | ❌ |
| Verify API | Coming soon | ❌ |
| Verify v2 API | Coming soon | ❌ |
| Video API | Coming soon | ❌ |
| Voice API | Coming soon | ❌ |

### Network APIS

| API | Supported? |
|-----------------------|:----------:|
| Number Verification | ❌ |
| SIM Swap | ❌ |

## Architecture

The SDK is organized into 3 crates:

- **`vonage-core`**: Core types, errors, authentication, and HTTP client functionality
- **`vonage-sms`**: SMS API implementation
- **`vonage`**: Unified SDK that re-exports all functionality

## Authentication

Supports:

- **Basic Auth**: API Key and Secret (for SMS API)
- **Signature Auth**: API Key and Signature Secret with MD5 signing (for SMS API)

## Regional Support

The SDK supports different API regions:

- `Region::UsEast` (default) - US East Coast
- `Region::EuWest` - Europe (Amsterdam)
- `Region::ApSoutheast` - Asia Pacific (Singapore)

## Documentation

- [API Documentation](https://docs.rs/vonage)
- [Vonage Developer Portal](https://developer.vonage.com)
- [SMS API Reference](https://developer.vonage.com/api/sms)

## Contributing

We welcome contributions! Please see [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines.

## License

This project is licensed under the Apache 2.0 License - see the [LICENSE](LICENSE.txt) file for details.