### Complete JSON-RPC Request-Response Workflow Source: https://context7.com/iorust/jsonrpc-lite/llms.txt Demonstrates a full client-server interaction: creating a request, serializing it, parsing on the server, processing, generating a response (success or error), serializing the response, and finally parsing and handling it on the client. ```rust use jsonrpc_lite::{JsonRpc, Error}; use serde_json::{json, to_string}; // Client: Create and serialize a request let request = JsonRpc::request_with_params(1, "add", json!([5, 3])); let request_json = to_string(&request).unwrap(); // Send request_json to server... // Server: Parse the request let parsed = JsonRpc::parse(&request_json).unwrap(); let method = parsed.get_method().unwrap(); let id = parsed.get_id().unwrap(); // Server: Process and create response let response = match method { "add" => { // Simulate processing let result = 5 + 3; JsonRpc::success(id, &json!(result)) }, _ => JsonRpc::error(id, Error::method_not_found()) }; let response_json = to_string(&response).unwrap(); // Output: {"jsonrpc":"2.0","result":8,"id":1} // Client: Parse and handle response let parsed_response = JsonRpc::parse(&response_json).unwrap(); if let Some(result) = parsed_response.get_result() { println!("Success: {}", result); } else if let Some(error) = parsed_response.get_error() { println!("Error {}: {}", error.code, error.message); } ``` -------------------------------- ### Create JSON-RPC Request With Parameters Source: https://context7.com/iorust/jsonrpc-lite/llms.txt Use `JsonRpc::request_with_params` to create a request including parameters. Parameters can be a JSON array for positional arguments or a JSON object for named arguments. ```rust use jsonrpc_lite::JsonRpc; use serde_json::{json, to_string}; // Request with array parameters (positional) let request = JsonRpc::request_with_params( 1, "subtract", json!([42, 23]) ); let json = to_string(&request).unwrap(); // Output: {"jsonrpc":"2.0","method":"subtract","params":[42,23],"id":1} ``` ```rust use jsonrpc_lite::JsonRpc; use serde_json::{json, to_string}; // Request with object parameters (named) let request = JsonRpc::request_with_params( "uuid-12345", "createUser", json!({ "username": "john_doe", "email": "john@example.com", "age": 30 }) ); let json = to_string(&request).unwrap(); // Output: {"jsonrpc":"2.0","method":"createUser","params":{"username":"john_doe","email":"john@example.com","age":30},"id":"uuid-12345"} ``` -------------------------------- ### Import jsonrpc-lite Crate Source: https://github.com/iorust/jsonrpc-lite/blob/master/README.md Import necessary components from the jsonrpc-lite crate for JSON-RPC 2.0 operations. This includes types for requests, responses, IDs, parameters, errors, and results. ```Rust use jsonrpc_lite::{JsonRPC, Id, Params, Error, ErrorCode, Result}; ``` -------------------------------- ### Create JSON-RPC Notification With Parameters Source: https://context7.com/iorust/jsonrpc-lite/llms.txt Use `JsonRpc::notification_with_params` to create a notification that includes parameters. Parameters can be a JSON object or array. ```rust use jsonrpc_lite::JsonRpc; use serde_json::{json, to_string}; // Notification with parameters let notification = JsonRpc::notification_with_params( "log", json!({ "level": "info", "message": "User logged in", "timestamp": "2024-01-15T10:30:00Z" }) ); let json = to_string(¬ification).unwrap(); // Output: {"jsonrpc":"2.0","method":"log","params":{"level":"info","message":"User logged in","timestamp":"2024-01-15T10:30:00Z"}} ``` ```rust use jsonrpc_lite::JsonRpc; use serde_json::{json, to_string}; // Notification with array parameters let notification = JsonRpc::notification_with_params( "update", json!([1, 2, 3, 4, 5]) ); let json = to_string(¬ification).unwrap(); // Output: {"jsonrpc":"2.0","method":"update","params":[1,2,3,4,5]} ``` -------------------------------- ### Create JSON-RPC 2.0 Error Responses Source: https://context7.com/iorust/jsonrpc-lite/llms.txt Use factory methods to create standard JSON-RPC 2.0 error responses. Ensure the correct error code and an appropriate ID are provided. ```rust use jsonrpc_lite::{JsonRpc, Error}; use serde_json::to_string; // Error response for method not found let response = JsonRpc::error(1, Error::method_not_found()); let json = to_string(&response).unwrap(); // Output: {"jsonrpc":"2.0","error":{"code":-32601,"message":"Method not found"},"id":1} ``` ```rust // Error response for invalid params let response = JsonRpc::error(2, Error::invalid_params()); let json = to_string(&response).unwrap(); // Output: {"jsonrpc":"2.0","error":{"code":-32602,"message":"Invalid params"},"id":2} ``` ```rust // Error response for parse error let response = JsonRpc::error((), Error::parse_error()); let json = to_string(&response).unwrap(); // Output: {"jsonrpc":"2.0","error":{"code":-32700,"message":"Parse error"},"id":null} ``` ```rust // Error response for invalid request let response = JsonRpc::error(3, Error::invalid_request()); let json = to_string(&response).unwrap(); // Output: {"jsonrpc":"2.0","error":{"code":-32600,"message":"Invalid request"},"id":3} ``` ```rust // Error response for internal error let response = JsonRpc::error(4, Error::internal_error()); let json = to_string(&response).unwrap(); // Output: {"jsonrpc":"2.0","error":{"code":-32603,"message":"Internal error"},"id":4} ``` -------------------------------- ### Create JSON-RPC Request Without Parameters Source: https://context7.com/iorust/jsonrpc-lite/llms.txt Use `JsonRpc::request` to create a request with a method name and identifier, but no parameters. Supports numeric, string, or null IDs. ```rust use jsonrpc_lite::JsonRpc; use serde_json::to_string; // Create a simple request with numeric ID let request = JsonRpc::request(1, "getStatus"); let json = to_string(&request).unwrap(); // Output: {"jsonrpc":"2.0","method":"getStatus","id":1} ``` ```rust use jsonrpc_lite::JsonRpc; use serde_json::to_string; // Create a request with string ID let request = JsonRpc::request(String::from("req-001"), "ping"); let json = to_string(&request).unwrap(); // Output: {"jsonrpc":"2.0","method":"ping","id":"req-001"} ``` ```rust use jsonrpc_lite::JsonRpc; use serde_json::to_string; // Create a request with null ID let request = JsonRpc::request((), "echo"); let json = to_string(&request).unwrap(); // Output: {"jsonrpc":"2.0","method":"echo","id":null} ``` -------------------------------- ### Create JSON-RPC Notification Without Parameters Source: https://context7.com/iorust/jsonrpc-lite/llms.txt Use `JsonRpc::notification` to create a JSON-RPC 2.0 notification. Notifications are fire-and-forget messages without an identifier. ```rust use jsonrpc_lite::JsonRpc; use serde_json::to_string; // Simple notification without parameters let notification = JsonRpc::notification("heartbeat"); let json = to_string(¬ification).unwrap(); // Output: {"jsonrpc":"2.0","method":"heartbeat"} ``` -------------------------------- ### Create JSON-RPC Success Response Source: https://context7.com/iorust/jsonrpc-lite/llms.txt Use `JsonRpc::success` to create a success response for a request. It requires the original request ID and the result, which can be any JSON-serializable value. ```rust use jsonrpc_lite::JsonRpc; use serde_json::{json, to_string}; // Success response with a simple value let response = JsonRpc::success(1, &json!(19)); let json = to_string(&response).unwrap(); // Output: {"jsonrpc":"2.0","result":19,"id":1} ``` ```rust use jsonrpc_lite::JsonRpc; use serde_json::{json, to_string}; // Success response with an object result let response = JsonRpc::success( "req-001", &json!({ "status": "ok", "data": { "userId": 12345, "name": "John Doe" } }) ); let json = to_string(&response).unwrap(); // Output: {"jsonrpc":"2.0","result":{"status":"ok","data":{"userId":12345,"name":"John Doe"}},"id":"req-001"} ``` -------------------------------- ### Inspect JSON-RPC Message Properties Source: https://context7.com/iorust/jsonrpc-lite/llms.txt Use accessor methods to inspect properties of JsonRpc request and response messages. These methods allow checking for version, ID, method, parameters, result, and error without pattern matching. ```rust use jsonrpc_lite::JsonRpc; use serde_json::json; // Create and inspect a request let request = JsonRpc::request_with_params(42, "calculate", json!({"x": 10, "y": 20})); assert_eq!(request.get_version(), Some("2.0")); assert_eq!(request.get_id(), Some(42.into())); assert_eq!(request.get_method(), Some("calculate")); assert!(request.get_params().is_some()); assert!(request.get_result().is_none()); // Only for success responses assert!(request.get_error().is_none()); // Only for error responses // Create and inspect a success response let response = JsonRpc::success(1, &json!({"sum": 30})); assert_eq!(response.get_version(), Some("2.0")); assert_eq!(response.get_id(), Some(1.into())); assert!(response.get_method().is_none()); // Only for requests/notifications assert!(response.get_params().is_none()); // Only for requests/notifications assert_eq!(response.get_result(), Some(&json!({"sum": 30}))); ``` -------------------------------- ### Work with JSON-RPC 2.0 Error Codes Source: https://context7.com/iorust/jsonrpc-lite/llms.txt The `ErrorCode` enum provides standard JSON-RPC 2.0 error codes and allows for custom server errors. Use `Error::new` with an `ErrorCode` variant to construct error objects. ```rust use jsonrpc_lite::error::{Error, ErrorCode}; // Create errors using ErrorCode let parse_error = Error::new(ErrorCode::ParseError); assert_eq!(parse_error.code, -32700); assert_eq!(parse_error.message, "Parse error"); let invalid_request = Error::new(ErrorCode::InvalidRequest); assert_eq!(invalid_request.code, -32600); let method_not_found = Error::new(ErrorCode::MethodNotFound); assert_eq!(method_not_found.code, -32601); let invalid_params = Error::new(ErrorCode::InvalidParams); assert_eq!(invalid_params.code, -32602); let internal_error = Error::new(ErrorCode::InternalError); assert_eq!(internal_error.code, -32603); // Create a custom server error (codes -32000 to -32099) let custom_error = Error::new(ErrorCode::ServerError(-32050)); assert_eq!(custom_error.code, -32050); assert_eq!(custom_error.message, "Server error"); ``` -------------------------------- ### Parse Single JSON-RPC Messages Source: https://context7.com/iorust/jsonrpc-lite/llms.txt Use `JsonRpc::parse` to deserialize a JSON string into a `JsonRpc` object. This method correctly identifies and handles requests, notifications, success responses, and error responses. Access message properties using getter methods. ```rust use jsonrpc_lite::JsonRpc; // Parse a request let input = r#"{"jsonrpc":"2.0","method":"subtract","params":[42,23],"id":1}"#; let message = JsonRpc::parse(input).unwrap(); // Access message properties assert_eq!(message.get_method(), Some("subtract")); assert_eq!(message.get_id(), Some(1.into())); assert!(message.get_params().is_some()); ``` ```rust // Parse a notification let input = r#"{"jsonrpc":"2.0","method":"update","params":[1,2,3]}"#; let message = JsonRpc::parse(input).unwrap(); assert_eq!(message.get_method(), Some("update")); assert_eq!(message.get_id(), None); // Notifications have no ID ``` ```rust // Parse a success response let input = r#"{"jsonrpc":"2.0","result":19,"id":1}"#; let message = JsonRpc::parse(input).unwrap(); assert_eq!(message.get_result(), Some(&serde_json::json!(19))); ``` ```rust // Parse an error response let input = r#"{"jsonrpc":"2.0","error":{"code":-32601,"message":"Method not found"},"id":1}"#; let message = JsonRpc::parse(input).unwrap(); assert!(message.get_error().is_some()); ``` -------------------------------- ### Parse Batch JSON-RPC Messages Source: https://context7.com/iorust/jsonrpc-lite/llms.txt Use `JsonRpc::parse_vec` to deserialize a JSON array string into a vector of `JsonRpc` objects. This is suitable for handling batch requests and responses. Iterate through the vector to process individual messages. ```rust use jsonrpc_lite::JsonRpc; // Parse a batch request let input = r#"[ {"jsonrpc":"2.0","method":"sum","params":[1,2,4],"id":"1"}, {"jsonrpc":"2.0","method":"notify_hello","params":[7]}, {"jsonrpc":"2.0","method":"subtract","params":[42,23],"id":"2"} ]"#; let batch = JsonRpc::parse_vec(input).unwrap(); assert_eq!(batch.len(), 3); // Process each message in the batch for message in &batch { match message.get_id() { Some(id) => println!("Request with ID: {:?}, method: {:?}", id, message.get_method()), None => println!("Notification: {:?}", message.get_method()), } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.