GREsau / okapi

OpenAPI (AKA Swagger) document generation for Rust projects
MIT License
606 stars 110 forks source link

Rocket Json does not implement JsonSchema for rocket special types error #60

Closed somehowchris closed 2 years ago

somehowchris commented 2 years ago

Hey :)

Due to some post on a ticket (which I currently do not find) I tried to implement this on one of my projects (which contains one of the special types things for rocket).

Now I have the following endpoint

#[openapi(tag="Orders")]
#[post("/", data = "<data>", format = "application/json")]
pub async fn create_order(
    db_state: &State<MongoState>,
    data: Json<CreateOrderRequest>,
) -> Result<Json<OrderResponse>, (Status, Json<ErrorMessage>)> {
    // some things happen...
}

For that I get the following error:

the trait bound `rocket::serde::json::Json<rust_common::models::rocket::ErrorMessage>: schemars::JsonSchema` is not satisfied

Well ErrorMessage Isn't a huge thing

#[derive(Serialize, Deserialize, std::fmt::Debug, JsonSchema)]
pub struct ErrorMessage {
    pub message: String,
    pub code: u16,
}

Am I doing something wrong? Other endpoints with the option of json do work

ralpha commented 2 years ago

Thanks, this was a bug, it needed to impl OpenApiResponderInner instead of JsonSchema (although JsonSchema is required for OpenApiResponderInner) but works a slightly different way. So things can now be nested as needed.

Also changed some of its logic to have this parsed correctly. Added some similar code to the "special-types" example to test this out. And works as expected now. Screenshot from 2021-10-10 19-50-57

It is a bit tricky to render this because the status code is dynamic (at runtime) so this can not be predicted in the docs. If this is not exactly what you like to see in the docs you can use similar approach as in the secure_request_guard. (this is useful if you know what kind of error codes you expect to be returned, because it is usually just a few anyway) See: https://github.com/GREsau/okapi/blob/master/examples/secure_request_guard/src/main.rs#L94:L102 and https://github.com/GREsau/okapi/blob/master/examples/secure_request_guard/src/main.rs#L174:L185

If you have more questions let me know.

somehowchris commented 2 years ago

Lovely, doped it into some APIs, just works like a charm. Many thanks @ralpha

ralpha commented 2 years ago

No problem. Thanks for the feedback and the other PR :)