QueryParam 在 Swagger API 中声明为不需要

我已经实现了一个包含这个方法的 Jax-RS 资源(使用 Dropwizard):


import javax.ws.rs.DefaultValue;

import javax.ws.rs.HeaderParam;

import javax.ws.rs.POST;

import javax.ws.rs.QueryParam;

import org.hibernate.validator.constraints.NotEmpty;

[...]


@POST

@Timed

public Prediction predict(

        @QueryParam("content") @NotEmpty String content,

        @HeaderParam("outputProbability") @DefaultValue("false") Boolean outputProbability) {

    return outputProbability ? getPredictionWithProb(content) : getPrediction(content);

}

在我的pom.xml,我添加了swagger-maven-plugin这样的:


        <plugin>

            <groupId>com.github.kongchen</groupId>

            <artifactId>swagger-maven-plugin</artifactId>

            <version>${swagger-maven-plugin-version}</version>

            <configuration>

                <apiSources>

                    <apiSource>

                        <springmvc>false</springmvc>

                        <schemes>

                            <scheme>http</scheme>

                        </schemes>

                        <locations>[...]</locations>

                        <info>[...]</info>

                        <swaggerDirectory>src/main/resources/swagger</swaggerDirectory>

                    </apiSource>

                </apiSources>

            </configuration>

            <executions>

                <execution>

                    <phase>compile</phase>

                    <goals>

                        <goal>generate</goal>

                    </goals>

                </execution>

            </executions>

        </plugin>

这一切都很好,除了content参数定义中的一行:


      "required" : false,

但是,该content字段显然是必需的。这在我调用服务时也得到了确认:如果content没有提供参数,则会抛出错误。


从这个答案中,似乎我可以通过使用 Swagger @ApiParam 注释明确声明该参数是必需的。但是,我不希望仅出于 Swagger API 定义的目的而引入额外的代码和依赖项。


这看起来是一个相当小的问题,但它可能表明我的代码中甚至swagger-maven-plugin. 我错过了什么吗?


Swagger 插件是否无法识别@org.hibernate.validator.constraints.NotEmpty注释?如果不是,Swagger@OpenAPI参数是否是根据 Swagger 插件的要求声明参数的唯一方法?


皈依舞
浏览 259回答 1
1回答

汪汪一只猫

我发现的唯一可行的解决方案是确实使用这样的@ApiParam注释:import io.swagger.annotations.ApiParam;[...]@POST@Timedpublic Prediction predict(&nbsp; &nbsp; &nbsp; &nbsp; @QueryParam("content") @NotEmpty @ApiParam(required = true) String content,&nbsp; &nbsp; &nbsp; &nbsp; @HeaderParam("outputProbability") @DefaultValue("false") Boolean outputProbability) {当然,这需要额外的 Swagger 依赖项(在 中pom.xml):&nbsp; &nbsp; <dependency>&nbsp; &nbsp; &nbsp; &nbsp; <groupId>io.swagger</groupId>&nbsp; &nbsp; &nbsp; &nbsp; <artifactId>swagger-annotations</artifactId>&nbsp; &nbsp; &nbsp; &nbsp; <version>1.5.21</version>&nbsp; &nbsp; </dependency>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java