4.5. OpenAPI 통합

4.5.1. 개요

OpenAPI 서비스를 사용하여 CamelContext 파일에서 REST 정의 경로 및 엔드포인트에 대한 API 문서를 생성할 수 있습니다. 이렇게 하려면 Java 기반인 camel-openapi-java 모듈과 함께 Camel REST DSL을 사용합니다. camel-openapi-java 모듈은 CamelContext와 통합된 서블릿을 생성하고 각 REST 끝점에서 정보를 가져와서 JSON 또는 YAML 형식의 API 문서를 생성합니다.

Maven을 사용하는 경우 pom.xml 파일을 편집하여 camel-openapi-java 구성 요소에 대한 종속성을 추가합니다.

<dependency>
   <groupId>org.apache.camel</groupId>
   <artifactId>camel-openapi-java</artifactId>
   <version>x.x.x</version>
   <!-- Specify the version of your camel-core module. -->
</dependency>

4.5.2. OpenAPI를 사용하도록 CamelContext 구성

Camel REST DSL에서 OpenAPI를 사용할 수 있도록 apiContextPath() 를 호출하여 OpenAPI 생성 API 문서의 컨텍스트 경로를 설정합니다. 예를 들면 다음과 같습니다.

public class UserRouteBuilder extends RouteBuilder {
    @Override
    public void configure() throws Exception {
        // Configure the Camel REST DSL to use the netty4-http component:
        restConfiguration().component("netty4-http").bindingMode(RestBindingMode.json)
            // Generate pretty print output:
            .dataFormatProperty("prettyPrint", "true")
            // Set the context path and port number that netty will use:
            .contextPath("/").port(8080)
            // Add the context path for the OpenAPI-generated API documentation:
            .apiContextPath("/api-doc")
                .apiProperty("api.title", "User API").apiProperty("api.version", "1.2.3")
                // Enable CORS:
                .apiProperty("cors", "true");

        // This user REST service handles only JSON files:
        rest("/user").description("User rest service")
            .consumes("application/json").produces("application/json")
            .get("/{id}").description("Find user by id").outType(User.class)
                .param().name("id").type(path).description("The id of the user to get").dataType("int").endParam()
                .to("bean:userService?method=getUser(${header.id})")
            .put().description("Updates or create a user").type(User.class)
                .param().name("body").type(body).description("The user to update or create").endParam()
                .to("bean:userService?method=updateUser")
            .get("/findAll").description("Find all users").outTypeList(User.class)
                .to("bean:userService?method=listUsers");
    }
}

4.5.3. OpenAPI 모듈 구성 옵션

아래 표에 설명된 옵션을 사용하여 OpenAPI 모듈을 구성할 수 있습니다. 다음과 같이 옵션을 설정합니다.

  • camel-openapi-java 모듈을 서블릿으로 사용하는 경우 web.xml 파일을 업데이트하고 설정할 각 구성 옵션에 init-param 요소를 지정하여 옵션을 설정합니다.
  • Camel REST 구성 요소에서 camel-openapi-java 모듈을 사용하는 경우 enableCORS(), host() 또는 contextPath() 와 같은 적절한 RestConfigurationDefinition 메서드를 호출하여 옵션을 설정합니다. RestConfigurationDefinition.apiProperty() 메서드를 사용하여 api.xxx 옵션을 설정합니다.
옵션유형설명

api.contact.email

문자열

API 관련 서신에 사용할 이메일 주소입니다.

api.contact.name

문자열

연결할 사람 또는 조직의 이름입니다.

api.contact.url

문자열

자세한 내용은 웹 사이트에 대한 URL입니다.

apiContextIdListing

부울

애플리케이션이 두 개 이상의 CamelContext 오브젝트를 사용하는 경우 기본 동작은 현재 CamelContext 에서만 REST 끝점을 나열하는 것입니다. REST 서비스를 실행 중인 JVM에서 실행 중인 각 CamelContext 의 REST 끝점 목록을 보려면 이 옵션을 true로 설정합니다. apiContextIdListing 이 true인 경우 OpenAPI는 /api-docs 와 같은 루트 경로에 CamelContext ID를 JSON 형식의 이름 목록으로 출력합니다. OpenAPI 생성 설명서에 액세스하려면 REST 컨텍스트 경로를 CamelContext ID(예: api-docs/myCamel )에 추가합니다. apiContextIdPattern 옵션을 사용하여 이 출력 목록의 이름을 필터링할 수 있습니다.

apiContextIdPattern

문자열

컨텍스트 목록에 CamelContext ID를 필터링하는 패턴입니다. 정규식을 지정하고 *를 와일드카드로 사용할 수 있습니다. 이는 Camel Intercept 기능에서 사용하는 것과 동일한 패턴 일치 기능입니다.

api.license.name

문자열

API에 사용되는 라이센스 이름입니다.

api.license.url

문자열

API에 사용되는 라이센스의 URL입니다.

api.path

문자열

문서를 생성할 REST API를 사용할 수 있는 경로를 설정합니다(예: /api-docs ). 상대 경로를 지정합니다. (예: http 또는 https )는 지정하지 마십시오. camel-openapi-java 모듈은 이 형식의 런타임 시 절대 경로를 계산합니다. protocol://host:port/context-path/api-path.

api.termsOfService

문자열

API 서비스 조건에 대한 URL입니다.

api.title

문자열

애플리케이션 이름입니다.

api.version

문자열

API 버전입니다. 기본값은 0.0.0입니다.

base.path

문자열

필수 항목입니다. REST 서비스를 사용할 수 있는 경로를 설정합니다. 상대 경로를 지정합니다. 즉, http 또는 https 와 같이 지정하지 마십시오. camel-openapi-java modul은 이 형식의 런타임 시 절대 경로를 계산합니다: protocol://host:port/context-path/base.path.

CORS

부울

CORS(HTTP 액세스 제어) 활성화 여부입니다. 이렇게 하면 REST API 문서를 보는 경우에만 CORS를 활성화하고 REST 서비스에 액세스할 수 없습니다. 기본값은 false입니다. 이 테이블 뒤에 설명된 대로 CorsFilter 옵션을 대신 사용하는 것이 좋습니다.

host

문자열

OpenAPI 서비스가 실행 중인 호스트의 이름을 설정합니다. 기본값은 localhost 를 기반으로 호스트 이름을 계산하는 것입니다.

스키마

문자열

사용할 프로토콜 체계입니다. 쉼표로 여러 값을 구분합니다(예: "http,https"). 기본값은 http 입니다.

opeapi.version

문자열

OpenAPI 사양 버전. 기본값은 3.0입니다.

4.5.4. JSON 또는 YAML 출력 가져오기

Camel 3.1부터 camel-openapi-java 모듈은 JSON 및 YAML 형식의 출력을 모두 지원합니다. 원하는 출력을 지정하려면 /openapi.json 또는 /openapi.yaml 을 요청 URL에 추가합니다. 요청 URL이 형식을 지정하지 않으면 camel-openapi-java 모듈은 HTTP Accept 헤더를 검사하여 JSON 또는 YAML을 허용할 수 있는지 여부를 감지합니다. 둘 다 허용되거나 지원되는 것으로 설정되지 않은 경우 JSON은 기본 반환 형식입니다.

4.5.5. 예

Apache Camel 3.x 배포에서 camel-example-openapi-cdicamel-example- openapi-java 모듈을 사용하는 방법을 보여줍니다.

Apache Camel 2.x 배포판에서 camel-example-swagger-cdicamel-example-swagger-java 모듈은 camel-swagger-java 모듈을 사용하는 방법을 보여줍니다.

4.5.6. OpenAPI에서 생성된 문서 개선

Camel 3.1부터 이름, 설명, 데이터 유형, 매개변수 유형과 같은 매개변수 세부 정보를 정의하여 OpenAPI에서 생성한 문서를 개선할 수 있습니다. XML을 사용하는 경우 이 정보를 추가할 param 요소를 지정합니다. 다음 예제에서는 ID 경로 매개변수에 대한 정보를 제공하는 방법을 보여줍니다.

<!-- This is a REST GET request to view information for the user with the given ID: -->
<get uri="/{id}" outType="org.apache.camel.example.rest.User">
     <description>Find user by ID.</description>
     <param name="id" type="path" description="The ID of the user to get information about." dataType="int"/>
     <to uri="bean:userService?method=getUser(${header.id})"/>
</get>

다음은 Java DSL의 예는 다음과 같습니다.

.get("/{id}").description("Find user by ID.").outType(User.class)
   .param().name("id").type(path).description("The ID of the user to get information about.").dataType("int").endParam()
   .to("bean:userService?method=getUser(${header.id})")

이름이 본문인 매개변수를 정의하는 경우 body 를 해당 매개변수 유형으로 지정해야 합니다. 예를 들면 다음과 같습니다.

<!-- This is a REST PUT request to create/update information about a user. -->
<put type="org.apache.camel.example.rest.User">
     <description>Updates or creates a user.</description>
     <param name="body" type="body" description="The user to update or create."/>
     <to uri="bean:userService?method=updateUser"/>
</put>

다음은 Java DSL의 예는 다음과 같습니다.

.put().description("Updates or create a user").type(User.class)
     .param().name("body").type(body).description("The user to update or create.").endParam()
     .to("bean:userService?method=updateUser")

Apache Camel 배포에서 examples/camel-example-servlet-rest-tomcat 도 참조하십시오.