Rust Program: Interacting with Web Service for Authentication & Data retrieval
Write a Rust program that interacts with a web service, performing authentication and data retrieval, propagating errors.
Sample Solution:
Rust Code:
use reqwest; // Import the reqwest crate for making HTTP requests
use std::error::Error; // Import the Error trait for error handling
// Function to perform authentication and retrieve data from the web service
fn retrieve_data(api_key: &str) -> Result> {
// Construct the URL for the web service endpoint
let url = format!("https://api.example.com/data?key={}", api_key);
// Perform a GET request to the web service endpoint
let response = reqwest::blocking::get(&url)?;
// Check if the request was successful (status code 200 OK)
if response.status().is_success() {
let body = response.text()?; // Extract the response body as a string
Ok(body) // Return the response body
} else {
Err(format!("Request failed with status code: {}", response.status()).into()) // Return an error message if the request was not successful
}
}
fn main() -> Result<(), Box> {
let api_key = "your_api_key_here"; // Replace "your_api_key_here" with your actual API key
// Call the function to retrieve data from the web service
match retrieve_data(api_key) {
Ok(data) => println!("Received data: {}", data), // Print the received data if the request was successful
Err(err) => eprintln!("Error retrieving data: {}", err), // Print an error message if the request failed
}
Ok(()) // Return Ok if the program completes successfully
}
Output:
Compiling playground v0.0.1 (/playground) Finished dev [unoptimized + debuginfo] target(s) in 2.78s Running `target/debug/playground` Error retrieving data: error sending request for url (https://api.example.com/data?key=your_api_key_here): error trying to connect: dns error: failed to lookup address information: Temporary failure in name resolution.
Explanation:
Here is a brief explanation of the above Rust code:
- First we use the "reqwest" crate to make HTTP requests to the web service.
- The "retrieve_data()" function constructs the URL with the API key, performs a GET request to the web service endpoint, and returns the response body if the request is successful.
- The "main()" function calls "retrieve_data()" with the API key and handles any errors during the process. If the retrieval is successful, it prints the received data; otherwise, it prints an error message. Finally, it returns an 'Ok' result if the program completes successfully.
Rust Code Editor:
Previous: Rust File Operations: Copy, Move, Delete with Error handling.
Next: Rust Configuration Parser: Apply Settings & Handle errors.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics