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.rs341 chars16 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:
136 chars4 lines
gistlibby LogSnag