api request in rust

To make an API request in Rust, we can use the Hyper crate which is a popular HTTP library in Rust. We can take advantage of Rust's async-await syntax to make non-blocking API requests. Here's an example code block that showcases how to perform an API request with Hyper in Rust:

main.rs
use hyper::{Body, Method, Request, Response, StatusCode, Uri, client::HttpConnector};
use hyper_tls::HttpsConnector;
use std::error::Error;
use tokio::io::BufReader;

async fn make_request() -> Result<(), Box<dyn Error>> {
    // Create a HTTPS connector to make requests to HTTPS endpoints
    let https = HttpsConnector::new();
    let client = hyper::Client::builder().build::<_, hyper::Body>(https);

    // Define the endpoint to call
    let uri = "https://api.example.com".parse::<Uri>()?;

    // Create a new request
    let mut request = Request::new(Body::empty());
    *request.method_mut() = Method::GET;
    *request.uri_mut() = uri.clone();

    // Send the request and get back the response
    let response = client.request(request).await?;

    // Read the response body
    let body = hyper::body::aggregate(response).await?;
    let string_body = String::from_utf8(body.bytes().to_vec())?;

    // Handle the response based on the status code
    match response.status() {
        StatusCode::OK => {
            println!("API response body: {}", string_body);
            Ok(())
        },
        _ => {
            eprintln!("API request failed: {}", string_body);
            Err("API request failed")?
        }
    }
}
1245 chars
38 lines

In the above code, we first create a HTTPS connector using the HttpsConnector from the hyper-tls crate which we use to make requests to HTTPS endpoints. We then create a new hyper::Client using the builder pattern and pass in our HTTPS connector.

Next, we define the API endpoint we want to call and create a new request using Request::new(). We set the method of the request to GET and the URI to the endpoint URI we defined earlier.

We then send the request using client.request() and wait for a response. We read the response body using hyper::body::aggregate() and convert it to a String.

Finally, we handle the response based on the status code. If the status is 200 OK, we print the response body to the console. If not, we print an error message to the console and return an error.

gistlibby LogSnag