Search code examples
rustrust-rocket

How can I return JSON from a Rust (Rocket) HTTP endpoint?


What is the easiest way to return Json via Rocket in Rust?

#[post("/route", data = "<data>")]
fn route(someVariable: String) -> String {
    // How can I return a json response here? {"a": "{someVariable}")
}

I tried: content::Json() but it seemed too static for me.


Solution

  • If you're finding content::Json() too static you can use the rocket_contrib package. Using this package will allow you to pass in a struct that implements Deserialize from the serde package

    use rocket_contrib::json::Json;
    use serde::Deserialize;
    
    #[derive(Deserialize)]
    struct User {
      name: String,
      age: u8,
      alive: bool, 
    }
    
    #[post("/route", data = "<data>")]
    fn route(someVariable: String) -> String {
        let user = User {
            name: "Jon Snow".to_string(),
            age: 21,
            alive: true,
        };
        Json(user_from_id)
    }
    

    Make sure you add the dependencies to your Cargo.toml

    serde = { version = "1.0", features = ["derive"] }
    rocket_contrib = "0.4"
    

    More information on rocket_contrib https://api.rocket.rs/v0.4/rocket_contrib/json/struct.Json.html