ask_nicely
A flexible and easy-to-use API client library
A flexible and easy-to-use API client library for Rust. This crate simplifies interacting with RESTful APIs by providing a structured approach to defining requests, handling authentication, and managing responses.
Installation
Add the following to your Cargo.toml file:
[]
= "0.1.0-rc.1" // Replace with the latest version
# Add other dependencies your crate requires, like tokio,serd, etc.
Key Features
- Declarative Request Definition: Define API requests as structs, leveraging Rust's type system for compile-time safety and clarity.
- Flexible Authentication: Supports various authentication methods, including Basic, Bearer, Digest, and API keys.
- Easy Request Building: Provides a builder pattern for constructing API clients with custom configurations like timeouts and redirect policies.
- Asynchronous Requests: Built on top of
reqwestfor efficient asynchronous HTTP requests. - Customizable Request Data: Supports sending data in various formats, including JSON, XML, form data, and binary payloads.
- Error Handling: Provides a clear error handling mechanism for both network and API-related errors.
- Macro-Generated Clients: Simplifies client creation with convenient macros.
Usage
1. Defining Requests
Use the #[derive(Request)] macro to define your API requests as structs. Specify the HTTP method, path, authentication requirements, and expected response type.
use *;
use ;
2. Creating an API Client
Use the gen_client macro to generate an API client with a specified base URL or an environment variable holding it.
use *;
// Or: #[gen_client(API_BASE_URL)]
;
3. Making Requests
use *;
async
4. Authentication
The Authentication enum provides several options:
- Basic(username, password)
- Digest(username, password)
- Bearer(token)
- ApiKeys(vec![(key1, value1), (key2, value2)])
- None
5. Error Handling
The request method returns a Result<Result<T, ApiError>, Error>. The outer Result handles network-related errors, while the inner Result handles API-specific errors (e.g., 404 Not Found). The ApiError struct contains the status code and response body, allowing for inspection and graceful error handling. Refer to the crate documentation for more details on error handling.