make a rest api request and parse the json result in rust

To make a REST API request and parse JSON response in Rust, we need to follow these steps:

  1. Add the reqwest and serde_json crates to your project's Cargo.toml file.
[dependencies]
reqwest = { version = "0.11.4", features = ["json"] }
serde_json = "1.0"
88 chars
4 lines
  1. Import the necessary crates.
main.rs
extern crate reqwest;
extern crate serde_json;

use reqwest::Error;
use serde_json::{Value};
93 chars
6 lines
  1. Write the function to make API request and parse JSON response.
main.rs
fn make_api_request(url: &str) -> Result<Vec<Value>, Error> {
    let client = reqwest::Client::new();
    let mut response = client.get(url).send()?;
    let json_response: Value = response.json()?;
    let results = json_response["results"].as_array().unwrap().to_vec();
    Ok(results)
}
291 chars
8 lines

Here, we are using reqwest::Client to create an HTTP client, making a GET request to the specified url, and deserializing the JSON response to Value using response.json(). We are then extracting the "results" key from the JSON response.

  1. Call the API function to make the request and parse the response.
main.rs
fn main() -> Result<(), Error> {
    let url = "https://jsonplaceholder.typicode.com/posts";
    let results = make_api_request(url)?;
    for result in results {
        println!("Title: {}", result["title"]);
    }
    Ok(())
}
230 chars
9 lines

Here, we are calling the make_api_request function to make the request to the specified API endpoint and parse the resulting JSON. We then loop through the parsed response and print out the titles of the posts.

This is a basic example of making a REST API request and parsing the JSON response in Rust using reqwest and serde_json crates.

gistlibby LogSnag