Search code examples
rustserderust-rocketokapi

How to return a Result type using rocket_okapi in Rust?


I am trying to create a web app that uses rocket_okapi to generate an openapi spec. I have defined some routes, but I cannot apply the openapi macro to them. Below is an example:

#[openapi]
#[get("/reading_lists")]
pub fn get_all_lists() -> Result<Json<Vec<DetailedReadingList>>, rocket::http::Status> {
    let reading_list = crate::db_ops::reading_lists::get_all_lists_detailed()
        .map_err(|_| rocket::http::Status::InternalServerError)?;
    Ok(Json(reading_list))
}

Here, DetailedReadingList is:

use chrono::NaiveDateTime;
use diesel::prelude::Queryable;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

#[derive(Queryable, Serialize, Deserialize, JsonSchema)]
pub struct DetailedReadingList {
    pub reading_list_id: i32,
    pub name: String,
    pub description: Option<String>,
    pub created_by: i32,
    pub created_at: NaiveDateTime,
    pub preview: Option<String>,
    pub participants: Vec<i32>,
}

This returns the following error:

error[E0277]: the trait bound `Result<rocket::serde::json::Json<std::vec::Vec<DetailedReadingList>>, rocket::http::Status>: OpenApiResponder<'_>` is not satisfied  

My Cargo.toml contains:

anyhow = "1.0.75"
chrono = { version = "0.4.26", features = ["serde"] }
diesel = { version = "2.1.0", features = ["postgres", "r2d2", "chrono"] }
dotenv = "0.15.0"
lazy_static = "1.4.0"
okapi = { version = "0.4.0", features = ["derive_json_schema"] }
rocket = { version = "0.5.0-rc.2", features = ["json"] }
rocket_okapi = { version = "0.5.1", features = [] }
schemars = { version = "0.8.12", features = ["chrono"] }
serde = { version = "1.0.183", features = ["derive"] }

I tried inverting the return type to be Json<Result...>, but I got a different error the trait Serializeis not implemented forStatus``


Solution

  • It looks like you're using rocket v0.5, while rocket_okapi only supports v0.4. Downgrade your rocket version or don't use this crate.