Sunday, November 12, 2017

Rust: Returning JSON with Rocket

Preamble
JSON is one of the technologies that, while very simple at its core, has had a profound impact on the technical landscape. Most modern public API's rely on JSON to transport information between application layers. It's become essential from everything ranging from Web API's, compiler technologies, and even data storage.

With that said, it's essential for an up-and-coming web tech stack like Rust and Rocket to support it. And support it they do.

Step 1: Install Dependencies
For some reason, the official Rocket documentation hides the fact that you need dependencies outside of rocket_codegen and rocket in order to return JSON.

You need to have all of the following lines in your Cargo.toml file:

rocket = "0.3.3"
rocket_codegen = "0.3.3"
rocket_contrib = "0.3.3"
Obviously, these versions will change over time. Without these dependencies, you may find yourself with errors such as:

"Cannot find macro json!", "Value cannot be found", etc. when following Rocket's documentation.

Step 2: Start returning JSON
Now, the easy part. I'm going to post the single most rudimentary example of a JSON return ever. In real web projects, you'll want to use serde and serde_derive to turn your data-transfer objects / models into a consistent JSON format. For now, we'll use the json! macro and Json struct to hard-return a value on the root route:

#[get("/")]fn index() -> Json<Value> {
    Json(json!({"value": 5}))
}

fn main() {
    rocket::ignite().mount("/", routes![index]).launch();}

No comments:

Post a Comment