标签: openapi

Spring Boot 3 和 OpenApi 3 (1.6.13) 不起作用。白标错误页面

我正在尝试使用 Spring Boot 3、Java 17、Open Api 3 查看 Swagger 页面。

我一定做错了什么,但是什么?是不是有什么不兼容的地方?

在 http://localhost:8080/v3/api-docs/ 或 http://localhost:8080/swagger-ui 我得到Whitelabel错误页面。

我正在从 Spring Boot 2.5 迁移,但为了确保我没有忘记删除导致此错误的某些内容,我从此处复制了一个教程https://www.techgeeknext.com/spring-boot/spring-boot- swagger3-example(我在这篇文章的末尾写了它)。

虽然运行了,但控制台中出现错误:

ERROR Class 'org.springframework.core.io.support.PathMatchingResourcePatternResolver' could not be processed by org.zeroturnaround.javarebel.integration.spring.core.cbp.PathMatchingResourcePatternResolverCBP@jdk.internal.loader.ClassLoaders$AppClassLoader@7a46a697: org.zeroturnaround.bundled.javassist.NotFoundException: retrieveMatchingFiles(..) is not found in org.springframework.core.io.support.PathMatchingResourcePatternResolver
    at org.zeroturnaround.bundled.javassist.CtClassType.getDeclaredMethod(SourceFile:1356)
    at org.zeroturnaround.javarebel.integration.spring.core.cbp.PathMatchingResourcePatternResolverCBP.registerScannedDirs(PathMatchingResourcePatternResolverCBP.java:255)
    at org.zeroturnaround.javarebel.integration.spring.core.cbp.PathMatchingResourcePatternResolverCBP.process(PathMatchingResourcePatternResolverCBP.java:41)
    at org.zeroturnaround.javarebel.integration.support.JavassistClassBytecodeProcessor.process(SourceFile:137)
    at org.zeroturnaround.javarebel.integration.support.CacheAwareJavassistClassBytecodeProcessor.process(SourceFile:34)
    at org.zeroturnaround.javarebel.integration.support.JavassistClassBytecodeProcessor.process(SourceFile:83)
    at com.zeroturnaround.javarebel.yg.a(SourceFile:413)
    at com.zeroturnaround.javarebel.yg.a(SourceFile:340)
    at com.zeroturnaround.javarebel.SDKIntegrationImpl.runBytecodeProcessors(SourceFile:44)
    at com.zeroturnaround.javarebel.vk.transform(SourceFile:140)
    at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:43009)
    at java.base/java.security.SecureClassLoader.defineClass(SecureClassLoader.java:150)
    at java.base/jdk.internal.loader.BuiltinClassLoader.defineClass(BuiltinClassLoader.java:862)
    at java.base/jdk.internal.loader.BuiltinClassLoader.findClassOnClassPathOrNull(BuiltinClassLoader.java:760)
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClassOrNull(BuiltinClassLoader.java:681)
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:639)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:520)
    at org.springframework.core.io.support.ResourceArrayPropertyEditor.<init>(ResourceArrayPropertyEditor.java:77)
    at …
Run Code Online (Sandbox Code Playgroud)

spring-boot openapi springdoc java-17

2
推荐指数
1
解决办法
2162
查看次数

TypeError:类型“type”的对象不可 JSON 序列化

该代码在 Postman 中运行良好,并提供有效的响应,但无法生成 OpenAPI/Swagger UI 自动文档。

class Role(str, Enum):
     Internal = "internal"
     External = "external"


class Info(BaseModel):
    id: int
    role: Role

class AppInfo(Info):
    info: str


@app.post("/api/v1/create", status_code=status.HTTP_200_OK)
async def create(info: Info, apikey: Union[str, None] = Header(str)):
    if info:
        alias1 = AppInfo(info="Portal Gun", id=123, role=info.role)
        alias2 = AppInfo(info="Plumbus", id=123, , role=info.role)
        info_dict.append(alias1.dict())
        info_dict.append(alias2.dict())

        
        return {"data": info_dict}
    else:
        
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Please provide the input"
        )
Run Code Online (Sandbox Code Playgroud)

收到错误:

TypeError: Object of type 'type' is not JSON serializable
Run Code Online (Sandbox Code Playgroud)

python swagger swagger-ui openapi fastapi

2
推荐指数
1
解决办法
3001
查看次数

无法在 Spring Boot 3 中使用 Openapi 打开 swagger-ui(Whitelabel 错误页面)

我在 Spring Boot 中通过 Openapi 打开 swagger-ui 时遇到问题。

当我尝试打开此 URL http://localhost:8080/swagger-ui.html 时,我收到Whitelabel 错误页面

我该如何解决这个问题?

这是pom.xml中定义的依赖项,如下所示。

<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-ui</artifactId>
    <version>1.6.4</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

这是如下所示的openpi 配置类

@Configuration
public class OpenApiConfig {

    @Bean
    public OpenAPI customOpenAPI(@Value("${application-description}") String description,
                                 @Value("${application-version}") String version) {
        return new OpenAPI()
                .info(new Info().title("API")
                        .version(version)
                        .description(description)
                        .license(new License().name("API Licence")));
    }
}
Run Code Online (Sandbox Code Playgroud)

这是如下所示的 application.properties 文件。

springdoc.swagger-ui.path=/swagger-ui.html
application-description=API Description
application-version=1.0

logging.level.org.springframework.web=DEBUG
logging.level.io.springfox=DEBUG
Run Code Online (Sandbox Code Playgroud)

当我尝试打开此 URL 时,出现以下错误http://localhost:8080/swagger-ui.html

2023-02-09T08:36:16.593+03:00 DEBUG 20184 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet        : GET "/swagger-ui.html", parameters={}
2023-02-09T08:36:16.594+03:00 …
Run Code Online (Sandbox Code Playgroud)

java swagger-ui spring-boot openapi springdoc-openapi-ui

2
推荐指数
1
解决办法
2828
查看次数

FastAPI 上是否可以有一个带有默认值的必需查询参数?

我试图设置一个必需的查询参数,但在 FastAPI 上给它一个默认值,但我在他们的用户指南上没有找到任何内容。

在 openapi 上,它会是这样的:

parameters:
      - name: "some_name"
        in: "query"
        description: "a description"
        required: true
        type: "string"
        default: "First"
        enum:
        - "First"
        - "Second"
        - "Third"
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,required 被分配为 true 并且我有一个默认值(“first”)使用 fastapi 我有这个:

class ModelNames(str, Enum):
  first = "first"
  second = "second"
  third = "third"


@app.post("/path")
async def this_function(
    modelInstance = Query(
      default=Required, # i would like to somehow assign "first" and Required to default 
      description="a description"
    )
  ):
  return None
Run Code Online (Sandbox Code Playgroud)

我尝试过直接分配“first”,但它使其成为可选的。

python swagger openapi fastapi

2
推荐指数
1
解决办法
1223
查看次数

OpenAPI 生成器 maven 插件不使用导入映射

我正在为 spring-boot 应用程序编写一个规范,以使用 openapi-generator-maven-plugin 为客户端生成 API。我想导入一些模型,因此我尝试像往常一样使用 schemaMappings 属性导入它们,就像我使用 openapi-generator-gradle-plugin 一样。在 yaml 规范中,我创建了要导入的模型的空架构,并在 pom.xml 的插件设置中指定了所需的类型。我的插件设置:

         <plugin>
            <groupId>org.openapitools</groupId>
            <artifactId>openapi-generator-maven-plugin</artifactId>
            <version>6.4.0</version>
            <executions>
                <execution>
                    <phase>generate-sources</phase>
                    <goals>
                        <goal>generate</goal>
                    </goals>
                    <configuration>
                        <inputSpec>${project.basedir}/src/main/resources/openapi/some-api.yaml</inputSpec>
                        <generatorName>spring</generatorName>
                        <output>${project.build.directory}/generated-sources/openapi</output>
                        <generateApiTests>false</generateApiTests>
                        <generateModelTests>false</generateModelTests>
                        <generateModelTests>false</generateModelTests>
                        <generateModelDocumentation>false</generateModelDocumentation>
                        <importMappings>
                            <importMapping>MyDto1=com.some.project.metric.MyDto1</importMapping>
                            <importMapping>MyDto2=com.some.project.metric.MyDto2</importMapping>
                        </importMappings>
                        <configOptions>
                            <title>Some project</title>
                            <library>spring-boot</library>
                            <useTags>true</useTags>
                            <dateLibrary>java8</dateLibrary>
                            <basePackage>${default.package}</basePackage>
                            <apiPackage>${default.package}.api</apiPackage>
                            <modelPackage>${default.package}.model</modelPackage>
                            <performBeanValidation>true</performBeanValidation>
                            <interfaceOnly>true</interfaceOnly>
                        </configOptions>
                    </configuration>
                </execution>
            </executions>
        </plugin>
Run Code Online (Sandbox Code Playgroud)

但突然我发现,由于某种原因,openapi-generator-maven-plugin 与 openapi-generator-gradle-plugin 不同,不使用 importMappings 属性。它存在于插件的代码中,您可以在生成器的配置或 configOptions 中使用它,但最终它不适用于我自己的 DTO。又检查了一遍。在 Gradle 中一切正常,但在 Maven 中则不然。它没有生成 POJO,因为它们是自由格式的对象,只是用对象类型替换它们。我开始深入研究这个问题,一段时间后我发现这个问题已经存在很长时间了。至少从 5.3.1 版本开始。你可以在这里看到

java import maven openapi openapi-generator-maven-plugin

2
推荐指数
1
解决办法
5571
查看次数

openapi java 生成器将 LocalDate 序列化为数组而不是完整日期

我在 spring 项目中使用 OpenAPI java 生成器 [1] 和 library:resttemplate, dateLibrary:java8 从规范生成客户端。

对于规范中的属性:

        targetDate:
          type: string
          format: date
Run Code Online (Sandbox Code Playgroud)

生成以下代码:

  public static final String JSON_PROPERTY_TARGET_DATE = "targetDate";

  private LocalDate targetDate;

  @javax.annotation.Nonnull
  @JsonProperty(JSON_PROPERTY_TARGET_DATE)
  @JsonInclude(value = JsonInclude.Include.ALWAYS)

  public LocalDate getTargetDate() {
    return targetDate;
  }

  @JsonProperty(JSON_PROPERTY_TARGET_DATE)
  @JsonInclude(value = JsonInclude.Include.ALWAYS)
  public void setTargetDate(LocalDate targetDate) {
    this.targetDate = targetDate;
  }
Run Code Online (Sandbox Code Playgroud)

我希望该字段能够序列化为完整日期,例如规范所承诺的“2023-01-01”:https: //spec.openapis.org/oas/v3.0.0#data-types。然而它实际上被序列化为一个数组:[2023,1,1]

同样的另一个属性

        otherDate:
          type: string
          format: date-time
Run Code Online (Sandbox Code Playgroud)

被序列化为自纪元以来的秒数,而不是全时。(我认为这是生成器中的错误)

由于生成了代码,我无法添加任何注释。我怎样才能确保日期正确序列化?

[1] openapi-generator-maven-plugin 6.3.0

java openapi jackson-databind openapi-generator openapi-generator-maven-plugin

2
推荐指数
1
解决办法
1905
查看次数

部署包含“文件”类型参数的端点时出错

我正在尝试部署一个包含类型参数的file简单端点。

我将gcloud service-management deploy命令与以下符合 openapi 的 yaml 一起使用:

swagger: "2.0"

info:
  description: "Image API"
  title: "Image API"
  version: "v1"

host: "image-api.endpoints.myproject.cloud.goog"
basePath: "/v1"

schemes:
- "https"

paths:
  "/images":
    post:
      description: "Adds an image"
      operationId: "add"
      consumes:
      - "multipart/form-data"      
      produces:
      - "application/json"
      responses:
        201:
          description: "An image create response"
          schema:
            $ref: "#/definitions/ImageResponse"
      parameters:
      - name: filepath
        in: formData
        required: true
        type: string
      - name: image
        in: formData
        required: false
        type: file

definitions:
  ImageResponse:
    type: object
    properties: …
Run Code Online (Sandbox Code Playgroud)

google-cloud-endpoints gcloud openapi google-cloud-endpoints-v2

1
推荐指数
1
解决办法
1184
查看次数

OpenAPI 3.0 - oneOf 内的 allOf

以下 YAML:

openapi: 3.0.0
info:
  title: test
  version: 1.0.0
paths:
  /test:
    get:
      summary: test
      responses:
        '200':
          description: Test
          content:
            application/json:
              schema:
                oneOf:
                  - allOf:
                    - type: object
                      properties:
                        firstA:
                          type: string
                    - type: object
                      properties:
                        firstB:
                          type: string
                  - allOf:
                    - type: object
                      properties:
                        secondA:
                          type: string
                    - type: object
                      properties:
                        secondB:
                          type: string
Run Code Online (Sandbox Code Playgroud)

在swagger 编辑器中根本不渲染。

ReDoc中它也无法正确渲染:

在此输入图像描述


如果allOf直接在其中嵌套多个实例oneOf是无效的,我如何使用有效的规范获得相同的结果?

swagger swagger-editor openapi

1
推荐指数
1
解决办法
4837
查看次数

Swagger/OpenAPI Bearer 身份验证与自定义标头名称

我正在使用 OpenAPI定义(小部分)现有 API ( Samanage ) 以协助一些集成工作。

我需要使用 Bearer auth 进行身份验证,但通过在Authorize.

服务器期望在一个X-Samanage-Authorization像这个例子一样命名的标头中进行承载身份验证:

curl -H "X-Samanage-Authorization: Bearer <TokenGoesHere>" -H 'Accept: application/vnd.samanage.v2.1+json' -H 'Content-Type: application/json' -X GET https://api.samanage.com/incidents.json
Run Code Online (Sandbox Code Playgroud)

我知道https://swagger.io/docs/specification/authentication/bearer-authentication/,但它似乎并没有完全帮助我。

这(OpenAPI 3)

components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT
...
security:
- bearerAuth: []
Run Code Online (Sandbox Code Playgroud)

生成名为 default ( Authorization)的身份验证标头

curl -X GET "https://api.samanage.com/incidents/12341234.json" -H "accept: application/json" -H "Authorization: Bearer <TokenGoesHere>"
Run Code Online (Sandbox Code Playgroud)

然后失败(401)。

我觉得我想要这个:

components:
  securitySchemes:
    bearerAuth:
      type: http
      name: X-Samanage-Authorization
      in: header
      scheme: bearer
Run Code Online (Sandbox Code Playgroud)

但这在 Swagger …

authentication swagger swagger-editor openapi

1
推荐指数
1
解决办法
4764
查看次数

openapi 3.0 中所有 API 的强制性标头

我在 Spring-boot 5 中使用 OpenAPI 3.0,因此没有配置 YAML。我有一个包含客户端标识 ID 的标头(这不是身份验证标头)。我想让它成为一个强制性的标题参数。在 OpenAPI 配置下方添加

@Configuration
public class OpenAPIConfiguration {
    @Bean
    public OpenAPI customOpenAPI() {

        return new OpenAPI()
                .components(new Components()
                        .addParameters("myCustomHeader", new Parameter().in("header").schema(new StringSchema()).required(true).description("myCustomHeader").name("myCustomHeader")))
                .info(new Info()
                        .title("My Rest Application")
                        .version("1.2.26"));
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,swagger UI 不会在任何 API 中显示所需的参数。有人可以帮助我做错什么吗?

在此处输入图片说明

swagger swagger-ui spring-boot openapi swagger-3.0

1
推荐指数
1
解决办法
3391
查看次数