# Swagger Documentation.
# Introduction
The OpenAPI specification is a standard way to describe RESTFul APIs. ExpressWebJs makes it easy to generate swagger documentation for your REST APIs.
# Installation
To begin using it, we first install the required dependency.
# Bootstrap
Once the installation process is complete, open app.ts in the root directory and enable swagger.
import SwaggerUI from "swagger-ui-express";
StartApp.withHttpServer({
swaggerOption: {
provider: SwaggerUI,
environment: "development",
swaggerUrl: "/api/docs",
},
});
# Configuration
Head over to Config/Swagger.ts to configure swagger.
import { env } from "expresswebcorets/lib/Env";
export default {
info: {
title: env("APP_NAME"),
version: "1.0",
description: "My website API docs with ExpressWebJs and Swagger",
license: {
name: "MIT",
url: "https://spdx.org/licenses/MIT.html",
},
contact: {
name: "",
},
},
host: "127.0.0.1:5100",
basePath: "/api",
};
# Examples
Now that swagger has been configured, we can now start documenting our api's.
Route.get("/welcome", (req: Request, res: Response) => {
//#swagger.description = "Welcome Endpoint";
res.send("Welcome to ExpressWebJs");
});
π‘ To see the changes take effect, you need to manually restart your application..
# Controller Route Documentation
All the components of a controller route can be documented. Starting from:
- Request path
- Request method
- Description
- Add a tag
- Responses
- Parameters
Let's document a create todo request.
/*
#swagger.start
#swagger.path = '/todos'
#swagger.method = 'post'
#swagger.description = 'Save todo'
#swagger.tags = ['Todo']
#swagger.responses[200] = {
description: 'Create todo success response',
schema: { $ref: "#/definitions/CreateTodoSuccessResponse" }
}
#swagger.responses[500]
#swagger.parameters['obj'] = {
in: 'body',
description: 'Todo data.',
required: true,
schema: { $ref: "#/definitions/CreateTodo" }
}
#swagger.end
*/
Route.post("/todos", "TodoController@createTodos");
π‘ ExpressWebJs uses swagger autogen to automatically generate your documentation. Visit swagger-autogen to read more on the parameters.
# Swagger Schema
From the above example, we added a CreateTodoSuccessResponse schema and CreateTodo schema. Does schemas need to be defined in Swagger configuration file.
import { env } from "expresswebcorets/lib/Env";
export default {
info: {
title: env("APP_NAME"),
version: "1.0",
description: "My website API docs with ExpressWebJs and Swagger",
license: {
name: "MIT",
url: "https://spdx.org/licenses/MIT.html",
},
contact: {
name: "",
},
},
host: "127.0.0.1:5100",
basePath: "/api",
definition: {
CreateTodo: {
$name: "Go to gym",
isComplete: true,
},
CreateTodoSuccessResponse: {
message: "Todo successfully created",
data: {
name: "Go to gym",
isComplete: true,
},
},
},
};