Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Guide on handling a type without ToSchema? #1264

Open
simbleau opened this issue Dec 27, 2024 · 1 comment
Open

Guide on handling a type without ToSchema? #1264

simbleau opened this issue Dec 27, 2024 · 1 comment

Comments

@simbleau
Copy link

In 4.x.x, this worked:

use stripe_product::{product::SearchProduct, Product};
use stripe_types::SearchList;

#[utoipa::path(
    get,
    path = "/stripe/get-credit-offers",
    responses(
        (status = 200, description = "Account created", body = [Product]),
    ),
    tag = "stripe"
)]
pub async fn get_credit_offers() -> Result<Json<SearchList<Product>>, LambdaError> { ... }

However, in 5.x.x, Product, which comes from a 3rd party crate, doesn't implement ToSchema. I found in the migration notes I would need to manually implement ToSchema, but honestly I have no idea how the type works and would like guidance on how I'm supposed to implement ToSchema manually.

@juhaku
Copy link
Owner

juhaku commented Dec 28, 2024

Yeah, this is an unfortunate necessity to support generics in the utoipa. This is a duplicate for this: #1205. While the issue and the following links inside the issue guide towards using value_type or utoipa-config for creating an alias for the type, you could also create a custom schema as well. For this you need a type to implement ToSchema for.

struct Foo;

impl PartialSchema for Foo {
  fn schema() -> RefOr<Schema> {
     Object::builder().property("name", Object::builder().schema_type(Type::String)).into()
    // or alternatively, since String implements ToSchema and PartialSchema we can directly refer the schema of a String.
    // Object::builder().property("name", String::schema()).into()
  }
}

impl ToSchema for Foo {
  fn name() -> Cow<'static, str> {
     Cow::Borrowed("Foo")
  }
}

In the above example there is a type Foo which implements PartialSchema that creates an OpenAPI object with one field name with type string. ToSchema implementation gives the Foo the name that is used to reference it within OpenAPI spec.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants