OpenAPI Specification (formerly known as Swagger Specification) is an API description format for REST APIs. An OpenAPI document allows developers to describe entirely an API.
Swagger UI is a graphical interface to visualize and interact with the API’s resources. It is automatically generated from one or several OpenAPI documents.
The first thing to do is to add the
@ApiInfo decorator to the root controller of the API. Two attributes are required: the
title of the application and the
version of the OpenAPI document.
Then each controller method can be documented with the
createOpenApiDocument(ApiController) will generate and return the below document (presented in YAML here but the actual returned value is a JS object). This function can be imported from the
@ApiOperation decorator can sometimes be cumbersome. That is why FoalTS provides other alternative decorators to improve code readability.
Large applications can have many subcontrollers. FoalTS automatically resolves the paths for you and allows you to share common specifications between several operations.
The document generated by
createOpenAPIDocument will then look like this:
The addition of these decorators can sometimes be quite redundant with existing hooks. For example, if we want to write OpenAPI documentation for authentication and validation of the request body, we may end up with something like this.
To avoid this, it is possible to generate the OpenAPI documentation from the validation and authentication hooks using the
More simply, you can globally set the configuration key
true so that each authentication and validation hooks generates documentation.
Note that this global configuration can always be override by setting the
openapi option on each hook.
Opening the browser at the path
/swagger will display the documentation of the
If needed, you can also specify the URL of a custom OpenAPI file (YAML or JSON).
Some applications may serve several APIs (for example two versions of a same API). Here is an example on how to handle this.
If you prefer to write manually your OpenAPI document, you can add an
openapi.yml file in the
public/ directory and configure your
SwaggerController as follows:
- FoalTS automatically resolves the path items and operations based on your controller paths.
- The decorators
@ApiExternalDocshave a different behavior depending on if they decorate the root controller or a subcontroller / a method.
Example with the root controller
Example with a subcontroller / a method
OpenAPI allows you to define and reuse components. Here is a way to achieve this with Foal.
@ApiDefineXXXdecorators can be added to any controllers or methods but they always define components in the global scope.
Common Error with
This example will throw this error.
OpenAPI does not support paths that are identical with different parameter names. Here is a way to solve this issue:
Swagger UI options can be extended using the