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

Viewed 3817

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.

2 Answers

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

Easiest way would be just using serde_json:

serde_json::to_string(&MyStructObject);

serde_json::to_string will return a Result< String > where the string is a json string. Finally in your Cargo.toml you need to have the following:

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

Related