Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions .github/workflows/rust.yml
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,32 @@ jobs:
run: cargo build --verbose
- name: Run tests
run: cargo test --verbose

fmt:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install rustfmt
run: rustup toolchain install stable --profile minimal --component rustfmt && rustup default stable
- name: Check formatting
run: cargo fmt --all --check

clippy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install clippy
run: rustup toolchain install stable --profile minimal --component clippy && rustup default stable
- name: Run clippy
run: cargo clippy --all-targets -- -D warnings

docs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install toolchain
run: rustup toolchain install stable --profile minimal && rustup default stable
- name: Build documentation
run: cargo doc --no-deps
env:
RUSTDOCFLAGS: -D warnings
10 changes: 10 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,13 @@ base64 = "0.13.0"
http = "0.2.9"
tokio = {version="1.28.1", features = ["rt", "macros"]}
serde_json = "1.0"

[lints.rust]
missing_docs = "warn"
rust_2018_idioms = { level = "warn", priority = -1 }
unreachable_pub = "warn"
unused_qualifications = "warn"

[lints.clippy]
pedantic = { level = "warn", priority = -1 }
use_self = "warn"
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ use std::collections::HashMap;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Initialize the client with your access token
let client = Client::new("<your_access_token>".to_string())?;
let client = Client::new("<your_access_token>")?;

// Make a request with parameters
let mut params = HashMap::new();
Expand Down
2 changes: 1 addition & 1 deletion docs/crates-io.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ use std::collections::HashMap;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Initialize the client with your access token
let client = Client::new("<your_access_token>".to_string())?;
let client = Client::new("<your_access_token>")?;

// Make a request with parameters
let mut params = HashMap::new();
Expand Down
33 changes: 17 additions & 16 deletions examples/api_calls.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,23 @@
//! Calls Openapi® APIs with a Bearer access token.

use openapi_sdk::Client;
use serde::Serialize;
use std::collections::HashMap;

#[derive(Serialize)]
struct Query {
country_code: String,
}

#[derive(Serialize)]
struct Payload {
limit: u64,
query: Query,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let token = "<your_access_token>".to_string();
let client = Client::new(token)?;
let client = Client::new("<your_access_token>")?;

let mut params = HashMap::new();
params.insert("denominazione", "altravia");
Expand All @@ -21,18 +33,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
)
.await?;

println!("API Response: {}", result);

#[derive(Serialize)]
struct Query {
country_code: String,
}

#[derive(Serialize)]
struct Payload {
limit: u64,
query: Query,
}
println!("API Response: {result}");

let query = Query {
country_code: "IT".to_string(),
Expand All @@ -48,7 +49,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
)
.await?;

println!("POST API Response: {}", result);
println!("POST API Response: {result}");

Ok(())
}
}
4 changes: 3 additions & 1 deletion examples/token_generation.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
//! Creates an Openapi® OAuth access token for a list of scopes.

use openapi_sdk::OauthClient;
use serde::{Deserialize, Serialize};

Expand All @@ -22,4 +24,4 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {

println!("Token created successfully!");
Ok(())
}
}
65 changes: 54 additions & 11 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use base64;
//! Rust client for the Openapi® marketplace APIs.

use http::header::{AUTHORIZATION, CONTENT_TYPE};
use http::HeaderMap;
use reqwest::Client as reqwest_client;
Expand All @@ -13,7 +14,7 @@ const OAUTH_BASE_URL: &str = "https://oauth.openapi.it";
// Base URL for test OAuth endpoint
const TEST_OAUTH_BASE_URL: &str = "https://test.oauth.openapi.it";

/// OAuth client for OpenAPI authentication and token management
/// OAuth client for Openapi® authentication and token management
pub struct OauthClient {
client: reqwest_client,
url: &'static str,
Expand All @@ -26,7 +27,15 @@ impl OauthClient {
/// * `username` - The API username
/// * `apikey` - The API key for authentication
/// * `test` - If true, uses test environment; otherwise production
pub fn new(username: &str, apikey: &str, test: bool) -> Result<OauthClient, reqwest::Error> {
///
/// # Errors
///
/// Returns an error if the underlying HTTP client cannot be built.
#[expect(
clippy::missing_panics_doc,
reason = "base64 credentials always form a valid header value"
)]
pub fn new(username: &str, apikey: &str, test: bool) -> Result<Self, reqwest::Error> {
// Select appropriate base URL based on environment
let url = if test {
TEST_OAUTH_BASE_URL
Expand All @@ -47,15 +56,19 @@ impl OauthClient {
let client = reqwest::Client::builder()
.default_headers(headers)
.build()?;
Ok(OauthClient { client, url })
Ok(Self { client, url })
}

/// Retrieves available OAuth scopes
///
/// # Arguments
/// * `limit` - If true, returns limited scope information
///
/// # Errors
///
/// Returns an error if the request fails or the response body cannot be read.
pub async fn get_scopes(&self, limit: bool) -> Result<String, reqwest::Error> {
let params = [("limit", limit as u8)];
let params = [("limit", u8::from(limit))];
let url = format!("{}/scopes", self.url);
let response: Response = self.client.get(url).query(&params).send().await?;
// TODO: Add error handling for non-2xx status codes with descriptive messages
Expand All @@ -68,6 +81,10 @@ impl OauthClient {
/// # Arguments
/// * `scopes` - List of permission scopes for the token
/// * `ttl` - Token lifetime in seconds
///
/// # Errors
///
/// Returns an error if the request fails or the response body cannot be read.
pub async fn create_token(
&self,
scopes: Vec<&'static str>,
Expand All @@ -92,6 +109,10 @@ impl OauthClient {
///
/// # Arguments
/// * `scope` - The scope to filter tokens by
///
/// # Errors
///
/// Returns an error if the request fails or the response body cannot be read.
pub async fn get_tokens(&self, scope: &'static str) -> Result<String, reqwest::Error> {
let params = [("scope", scope)];
let url = format!("{}/token", self.url);
Expand All @@ -105,6 +126,10 @@ impl OauthClient {
///
/// # Arguments
/// * `id` - The unique identifier of the token to delete
///
/// # Errors
///
/// Returns an error if the request fails or the response body cannot be read.
pub async fn delete_token(&self, id: String) -> Result<String, reqwest::Error> {
let url = format!("{}/token/{}", self.url, id);
let response: Response = self.client.delete(url).send().await?;
Expand All @@ -118,6 +143,10 @@ impl OauthClient {
/// # Arguments
/// * `period` - The time period (e.g., "day", "month")
/// * `date` - The date in appropriate format
///
/// # Errors
///
/// Returns an error if the request fails or the response body cannot be read.
pub async fn get_counters(
&self,
period: &'static str,
Expand All @@ -141,7 +170,15 @@ impl Client {
///
/// # Arguments
/// * `token` - The Bearer token for API authentication
pub fn new(token: String) -> Result<Client, reqwest::Error> {
///
/// # Errors
///
/// Returns an error if the underlying HTTP client cannot be built.
///
/// # Panics
///
/// Panics if `token` contains characters that are not valid in an HTTP header value.
pub fn new(token: &str) -> Result<Self, reqwest::Error> {
let auth_header = format!("Bearer {token}");
let mut headers = HeaderMap::new();

Expand All @@ -153,7 +190,7 @@ impl Client {
let client = reqwest::Client::builder()
.default_headers(headers)
.build()?;
Ok(Client { client })
Ok(Self { client })
}

/// Makes an HTTP request to the specified URL
Expand All @@ -166,6 +203,14 @@ impl Client {
///
/// # Returns
/// The response body as a JSON string
///
/// # Errors
///
/// Returns an error if the request fails or the response body cannot be read.
///
/// # Panics
///
/// Panics if `method` is not a valid HTTP method.
pub async fn request<T>(
&self,
method: &str,
Expand All @@ -176,8 +221,6 @@ impl Client {
where
T: Serialize,
{
let url = format!("{}", url);

// TODO: Replace unwrap() with proper error handling for invalid HTTP methods
// Consider returning a descriptive error like "Invalid HTTP method: {method}"
let mut request = self.client.request(Method::from_str(method).unwrap(), url);
Expand Down Expand Up @@ -215,11 +258,11 @@ mod tests {
/// Tests successful creation of API client with Bearer token
#[test]
fn test_api_client_creation() {
let client = Client::new("test_token".to_string());
let client = Client::new("test_token");
assert!(client.is_ok());
}

// TODO: Add test for invalid credentials and verify error messages are descriptive
// TODO: Add test for invalid HTTP method in request() and verify error handling
// TODO: Add integration tests for API endpoints with mock server
}
}