Adding Swagger to a project
Overview
Swagger is an API documentation tool which lets you test REST APIs.
Getting Started
For an existing project it is enough to simply run the add command with the swagger param to generate the necessary files. You will be prompted to decide if you want to use the automatic generation of the documentation or if you want to use a swagger.json. If you choose yes the template will be generated for you as well as the endpoint configuration will be added to the archibald.json.
archibald add swagger
The scaffolder is built into @archibald/cli and sets up everything Swagger-related:
- per-platform Swagger UI templates under
src/{platform}/server/template/swagger/(index.twig,error.twig), - an optional per-platform
swagger.jsonendpoint file (the command asks whether you want one), - the
cli.swaggerconfiguration inarchibald.jsonpointing at the scaffolded template/endpoint paths.
Swagger generation itself needs no extra dependencies: the OpenAPI spec is derived from each
route's zod validation by the Swagger plugin built into @archibald/server (see the
server runtime).
{
"cli": {
"swagger": {
"index": "src/{platform}/server/template/swagger/index.twig",
"error": "src/{platform}/server/template/swagger/error.twig",
"endpoint": "src/{platform}/swagger.json"
}
}
}
If you opt for the automatic generation you will need to add a tag to each path you want to include in the documentation, like so:
const CartServerRouteConfig: DefaultRouteConfig[] = [
{
method: RouteMethod.GET,
path: `${base}/{version}/users/carts`,
handler: 'CartController.getCart',
options: {
tags: ['api']
}
}
];
The Archibald Swagger Plugin has to be registered in registerPlugin method of your Server class. To do that import SwaggerPlugin from @archibald/server:
class Server extends CoreServer {
protected override async registerPlugins() {
await super.registerPlugins([...DefaultPlugins, ...SwaggerPlugin]);
Logger.info('Plugins registered');
}
}
That's it! Your swagger documentation is available under /swagger-docs.