make an external api call in rust

To make an external API call in Rust, you can use the reqwest crate, which provides a simple HTTP client interface. Here's an example function that makes an API call and deserializes the response into a Rust struct using the serde crate:

main.rs
use reqwest::Error;
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize)]
struct ResponseData {
    id: String,
    name: String,
    // ...
}

async fn fetch_data() -> Result<ResponseData, Error> {
    let url = "https://api.example.com/data";
    let response = reqwest::get(url).await?.json().await?;
    Ok(response)
}
341 chars
16 lines

In this example, the fetch_data function makes an HTTP GET request to the URL "https://api.example.com/data", and deserializes the JSON response into a ResponseData struct using the serde crate's Deserialize derive. The function returns a Result<ResponseData, Error>, where Error is the error type returned by the reqwest crate.

Note that this example uses the async keyword and the await keyword to make the API call asynchronously. To use these keywords, you'll need to be working with an appropriate version of Rust (such as Rust 1.39 or later) and enable the async-await feature in your Cargo.toml file:

[dependencies]
reqwest = { version = "0.11.4", features = ["blocking", "json"] }
serde = { version = "1.0.130", features = ["derive"] }
136 chars
4 lines

gistlibby LogSnag