You can watch my latest video below to learn how to consume JSON APIs with Rustlang and the reqwest library. I made this tutorial because I had a bit of a hard time finding out how to work with nested JSON and reqwest. I couldn't find an example as I was working out the problem on my own so I would like to share what I found with you. This example uses the Pokemon API
extern crate reqwest;
extern crate serde_json;
#[macro_use] extern crate serde_derive;
#[derive(Deserialize)]
pub struct Pokemon {
abilities: Vec<PokeAPIAbilities>,
species: PokeAPISpecies
}
#[derive(Deserialize)]
struct PokeAPISpecies {
name: String
}
#[derive(Deserialize)]
struct PokeAPIAbilities {
ability: PokeAPIAbility,
is_hidden: bool
}
#[derive(Deserialize)]
struct PokeAPIAbility {
name: String
}
pub fn get_pokemon_data() -> Pokemon {
let endpoint = "https://pokeapi.co/api/v2/pokemon/litwick";
let client = reqwest::Client::new();
let res = client.get(endpoint).send();
let pokemon: Pokemon = res.unwrap().json().unwrap();
pokemon
}
fn main() {
let pokemon = get_pokemon_data();
println!("Name: {}", pokemon.species.name);
println!("Abilities:");
for a in pokemon.abilities {
println!("{};\tHidden: {}", a.ability.name, a.is_hidden);
}
}