How to return an array of objects queried from external API in Rocket

889 Views Asked by At

I'm new to Rust, and wanted to test it out with something simple. The code basically queries an external API and returns the response. In this case, the response is an array of objects.

#![feature(proc_macro_hygiene, decl_macro)]

#[macro_use] extern crate rocket;
extern crate serde;
extern crate serde_json;

#[derive(Deserialize, Debug)]
struct InboundAddress {
    chain: String,
    pub_key: String,
    address: String,
    halted: bool,
    gas_rate: String,
}

#[get("/addresses")]
fn addresses() -> Result<Vec<InboundAddress>, reqwest::Error> {
    let url = "https://midgard.thorchain.info/v2/thorchain/inbound_addresses";
    let addresses: Vec<InboundAddress> = reqwest::blocking::get(url)?.json()?;
    println!("First address chain is: {}", addresses[0].chain);
    Ok(addresses)
}


fn main() {
    rocket::ignite().mount("/", routes![addresses]).launch();
}

The error is coming from what I'm trying to return, Result<Vec<InboundAddress>, reqwest::Error>, saying "the trait rocket::response::Responder<'_> is not implemented for std::result::Result<std::vec::Vec<InboundAddress>, reqwest::Error>"

The json is parsing correctly, logging out details from some of the addresses work. How can I return the array of objects queried from an external API in Rocket?

1

There are 1 best solutions below

1
On

The key was wrapping the Vec in Json.

#[get("/addresses")]
fn addresses() -> Result<Json<Vec<InboundAddress>>, reqwest::Error> {
    let url = "https://testnet.midgard.thorchain.info/v2/thorchain/inbound_addresses";
    let addresses: Vec<InboundAddress> = reqwest::blocking::get(url)?.json()?;
    Ok(Json(addresses))
}