RevTpark
RevTpark

Reputation: 75

Error while rocket implementation for creating a basic API

I have been programming in Rust for a month or so and now I wanted to try out API's using Rocket in rust. I tried to implement the below code but I got the error the trait bound \Json<Test>: Responder<'_, '_> is not satisfied . Not quite sure what I did wrong I tried to find out a reason for it but couldn't get any. I am referring to this video and this guide, according to which I did everything correct.

Also side note: I use extern crate rocket but it still does not recognize Build, routes, etc. Any solution to this as well?

#![feature(proc_macro_hygiene, decl_macro)]

#[macro_use]
extern crate rocket;

use rocket::*;
use rocket_contrib::json::Json;
use serde_json::json;

struct Test{
    name: String,
}

#[get("/")]
fn hello_world() -> Json<Test> {
    let test: Test = Test { name: String::from("Test54") };
    Json(test)
}

#[launch]
fn rocket() -> Rocket<Build> {
    rocket::build()
        .mount(
            "/",
            routes![hello_world]
        )
}

cargo.toml

[package]
name = "backend"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
name = "lib"
path = "src/lib.rs"

[[bin]]
name = "backend"
path = "src/bin.rs"

[dependencies]
rocket = "0.5.0-rc.1"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"

[dependencies.rocket_contrib]
version = "0.4"
default-features = false
features = ["json"]

error log

error[E0277]: the trait bound `Json<Test>: Responder<'_, '_>` is not satisfied
   --> src/bin.rs:19:21
    |
19  | fn hello_world() -> Json<Test> {
    |                     ^^^^^^^^^^ the trait `Responder<'_, '_>` is not implemented for `Json<Test>`
    |
    = help: the following other types implement trait `Responder<'r, 'o>`:
              <&'o [u8] as Responder<'r, 'o>>
              <&'o str as Responder<'r, 'o>>
              <() as Responder<'r, 'static>>
              <(ContentType, R) as Responder<'r, 'o>>
              <(Status, R) as Responder<'r, 'o>>
188 |     pub fn from<R: Responder<'r, 'o>>(req: &'r Request<'_>, responder: R) -> Outcome<'r> {
    |                    ^^^^^^^^^^^^^^^^^ required by this bound in `route::handler::<impl Outcome<rocket::Response<'o>, Status, rocket::Data<'o>>>::fr
om`

For more information about this error, try `rustc --explain E0277`.

Upvotes: 0

Views: 345

Answers (1)

user2722968
user2722968

Reputation: 16475

rocket_contrib::json::Json only implements rocket::response::Responder if the T it contains implements serde::ser::Serialize (due to this). Currently, your Teststruct does not implement Serialize, so Json<Test> does not implement Responder; this is what the compiler is complaining about.

You can easily implement Serialize for Test by deriving it:

use serde::Serialize;

#[derive(Serialize)]
struct Test {
    name: String,
}

Upvotes: 1

Related Questions