Getting JSON from a URL and printing it to the console

I want to fetch JSON from an API like https://api.mocki.io/v1/ce5f60e2 , parse it, and just print it out to the console, what crate/methods can I use to achieve this simple task? A little working code snippet with respective packages used will be greatly appreciated.

In this case the console prints : {"city":"Stockholm","name":"Lennart Johansson"}

Thanks.

You can use reqwest.

[dependencies]
reqwest = { version = "0.11", features = ["blocking"] }

then you can use the reqwest::blocking::get method like this:

fn main() {
    let response = reqwest::blocking::get("https://api.mocki.io/v1/ce5f60e2").unwrap();
    println!("{}", response.text().unwrap());
}
{"city":"Stockholm","name":"Lennart Johansson"}

To parse the json and get the values out of the object, do this:

[dependencies]
reqwest = { version = "0.11", features = ["blocking", "json"] }
serde = { version = "1", features = ["derive"] }
use serde::Deserialize;

#[derive(Debug, Deserialize)]
struct MyStruct {
    city: String,
    name: String,
}

fn main() {
    let response = reqwest::blocking::get("https://api.mocki.io/v1/ce5f60e2").unwrap();
    let var: MyStruct = response.json().unwrap();
    println!("{:?}", var);
}
MyStruct { city: "Stockholm", name: "Lennart Johansson" }
4 Likes

Thank you @alice .

Well, if you pay attention to all the errors, the actual problem is the other error that you probably have

error: cannot find derive macro `Deserialize` in this scope
 --> src/main.rs:1:17
  |
1 | #[derive(Debug, Deserialize)]
  |                 ^^^^^^^^^^^

This can be made working by adding the missing use statement:

use serde::Deserialize;

I’m just guessing here. Sorry if I’m guessing incorrectly, and the other error is completely unrelated. In any case, you must have copied something incorrectly since Alice’s code does compile without problems.

2 Likes

Sorry, the exact same code was giving me issues, tried a fresh project and it worked.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.