fetch pokemons from online api to array in rust

To fetch Pokemon data from an online API in Rust and store it in an array, we can use the reqwest crate for making HTTP requests and parsing the JSON response. Here's an example code block that fetches the first 10 Pokemon from the PokeAPI and stores their names in an array:

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

#[derive(Serialize, Deserialize)]
struct Pokemon {
    name: String,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let response = reqwest::get("https://pokeapi.co/api/v2/pokemon?limit=10").await?;
    let pokemon_list = response.json::<PokemonList>().await?;
    let pokemon_names: Vec<String> = pokemon_list
        .results
        .into_iter()
        .map(|pokemon| pokemon.name)
        .collect();
    println!("{:?}", pokemon_names);
    Ok(())
}

#[derive(Serialize, Deserialize)]
struct PokemonList {
    results: Vec<Pokemon>,
}
624 chars
26 lines

In this example, we define a Pokemon struct with only the name field, which is the only data we're interested in. We also define a PokemonList struct that contains a vector of Pokemon structs.

We make an HTTP GET request to the PokeAPI URL that returns the first 10 Pokemon, and then deserialize the response into a PokemonList struct using the json method provided by reqwest.

Finally, we map the Pokemon structs into a vector of strings containing only the Pokemon names, and print the resulting array.

related categories

gistlibby LogSnag