== OpenAPI

This module helps automating the generation of API documentation using Jooby projects. jooby-openapi works by examining an application at *build* time to infer API semantics based on byte code and optional annotations.

Automatically generates documentation in JSON/YAML format APIs. This documentation can be completed by comments using swagger-api annotations.

This library supports:

- https://swagger.io/specification[OpenAPI 3] (json and yaml)
- https://swagger.io/tools/swagger-ui[Swagger UI] (Optional)
- https://github.com/Redocly/redoc[Redoc] (Optional)

=== Configuration

.pom.xml
[source, xml, role = "primary", subs="verbatim,attributes"]
----
<properties>
  <application.class>myapp.App</application.class>
</properties>
...
<plugins>
  ...
  <plugin>
    <groupId>io.jooby</groupId>
    <artifactId>jooby-maven-plugin</artifactId>
    <version>{joobyVersion}</version>
    <executions>
      <execution>
        <goals>
          <goal>openapi</goal>
        </goals>
      </execution>
    </executions>
  </plugin>
</plugins>
----

.build.gradle
[source, groovy, role = "secondary", subs="verbatim,attributes"]
----
buildscript {

  repositories {
    mavenCentral()
  }

  dependencies {
    classpath "io.jooby:jooby-gradle-plugin:{joobyVersion}"
  }
}

apply plugin: "application"
apply plugin: "jooby"

...
mainClassName = "myapp.App"
...

// Run openAPI task on joobyRun
joobyRun.dependsOn openAPI

// Run openAPI task on build
build.dependsOn openAPI
----

[NOTE]
====
Most of this setup is not required if you already have `joobyRun` on your build.
====

=== Usage

To learn how it works, let's write a simple Pet API:

.Java
[source, java, role="primary"]
----
{
  install(new OpenAPIModule());        <1>

  path("/pets", () {                   <2>

    get("/", ctx -> {
      PetRepository repo = ...;
      return repo.list();
    });

  });
}
----

.Kotlin
[source, kt, role="secondary"]
----
{
  install(OpenAPIModule())             <1>

  path("/pets") {                      <2>

    get("/") {
       val repo = ...;
       repo.list()
    }

  }
}
----

<1> Install `OpenAPIModule`
<2> Write your API

The javadoc:OpenAPIModule[] read from classpath the generated `json` and `yaml` files. To generate
them you need to build your project.

.Maven
    mvn clean package

.Gradle
    ./gradlew build

You will find the files in the output build directory. If your application is `bar.Foo`, then:

.Maven
    target/classes/bar/Foo.json
    target/classes/bar/Foo.yaml

.Gradle
    build/classes/java/main/bar/Foo.json
    build/classes/java/main/bar/Foo.yaml

[NOTE]
====
This is the main difference with previous version. We moved from runtime to build time generation. This way we:

- Are able to get our OpenAPI files at build time (of course)
- At runtime we don't waste resources (CPU, memory) while analyze and build the OpenAPI model
- We keep bootstrap as fast as possible
====

The OpenAPI generator works exactly the same for MVC routes (a.k.a Controller):

.Java
[source, java, role="primary"]
----
{
  install(new OpenAPIModule());

  mvc(new Pets());
}

@Path("/pets")
public class Pets {
  
  @GET
  public List<Pet> list() {
    ...
  }
  
}
----

.Kotlin
[source, kt, role="secondary"]
----
{
  install(OpenAPIModule())

  mvc(new MyController())
}

@Path("/pets")
class Pets {
  
  @GET
  fun list(): List<Pet> {
    ...
  }
  
}
----

The Maven plugin and Gradle task provide two filter properties `includes` and `excludes`. These
properties filter routes by their path pattern. The filter is a regular expression.

=== Annotations

To produces a better documentation this plugin depends on some OpenAPI annotations. To use them, you
need to add a dependency to your project:

[dependency, artifactId="swagger-annotations"]
.

Once you added to your project, you can annotate your routes:

.Script
[source,java,role="primary"]
----
import io.swagger.v3.oas.annotations.Operation;
...

public class App extends Jooby {
  {
    path("/pets", () -> {
      
      get("/{id}", this::findPetById)

    });
  }

  @Operation(
      summary = "Find a pet by ID",
      description = "Find a pet by ID or throws a 404"
  )
  public Pet findPetById(Context ctx) {
    PetRepo repo = require(PetRepo.class);
    long id = ctx.path("id").longValue();
    return repo.find(id);
  }
}
----

.Kotlin
[source,kotlin,role="secondary"]
----
import io.swagger.v3.oas.annotations.Operation

class App :Kooby({
  path("/pets") {
  
    get("/{id}", ::findPetById)

  }
})

@Operation(
  summary = "Find a pet by ID",
  description = "Find a pet by ID or throws a 404"
)
fun findPetById(ctx: Context) : Pet {
  val repo = ...
  val id = ctx.path("id").longValue()
  return repo.find(id)
}
----

The OpenAPI annotations complement the openAPI byte code parser by adding documentation
or being more specific about a operation, parameter, response type, response status, etc.

Annotations works as documentation but also as a way to override what was generated by the byte
code parser.

Annotations are supported at script routes (using the technique described before) and mvc routes.

If you look at the example, there is no documentation for path parameter: `id`, still this parameter
is going to be present in the OpenAPI files (present, but without documentation).

To add documentation just do:

----
@Operation(
  summary = "Find a pet by ID",
  description = "Find a pet by ID or throws a 404",
  parameters = @Parameter(description = "Pet ID")
)
----

If the parameter annotation doesn't specify a name, parameter binding follows a positional assignment.

==== Responses & Status

The default response code is `Success(200)` (or `NO_CONENT(204)` for DELETE mvc routes). Now, if
you need to:

- document the default response
- use a custom response code
- use multiple response codes

You need the `ApiResponse` annotation:

.Document default response:
----
@ApiResponse(description = "This is the default response")
----

.Use a custom response code:
----
@ApiResponse(responseCode = "201", description = "This is the default response")
----

.Multiple response codes:
----
@ApiResponses({
  @ApiResponse(description = "This is the default response"),
  @ApiResponse(responseCode = "500"),
  @ApiResponse(responseCode = "400"),
  @ApiResponse(responseCode = "404")
})
----

=== Documentation Template

The OpenAPI output generates some default values for `info` and `server` section. It generates
the necessary to follow the specification and produces a valid output. These sections can be override
with better information/metadata.

To do so just write an `openapi.yaml` file inside the `conf` directory the we are going to use it
as template.

.conf/openapi.yaml
[source, yaml]
----
openapi: 3.0.1
info:
  title: My Super API
  description: |
    Nunc commodo ipsum vitae dignissim congue. Quisque convallis malesuada tortor, non
    lacinia quam malesuada id. Curabitur nisi mi, lobortis non tempus vel, vestibulum et neque.

    ...
  version: "1.0"
  license:
    name: Apache 2.0
    url: http://www.apache.org/licenses/LICENSE-2.0.html
----

All sections from template file (except the paths section) are merged into the final output.

=== UI

==== Swagger UI

To use swagger-ui just add the dependency to your project:

[dependency, artifactId="jooby-swagger-ui"]
.

The swagger-ui application will be available at `/swagger`. To modify the default path, just call javadoc:OpenAPIModule[swaggerUI, java.lang.String]

==== Redoc

To use redoc just add the dependency to your project:

[dependency, artifactId="jooby-redoc"]
.

The redoc application will be available at `/redoc`. To modify the default path, just call javadoc:OpenAPIModule[redoc, java.lang.String]
