Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/olivierlsc/swagger-express-ts

Generate and serve swagger.json
https://github.com/olivierlsc/swagger-express-ts

documentation express express-js inversify inversifyjs javascript json nodejs rest rest-api swagger swagger2 typescript

Last synced: about 1 month ago
JSON representation

Generate and serve swagger.json

Awesome Lists containing this project

README

        

![](wiki/img/logo.png)

# swagger-express-ts
Automatically generate and serve swagger.json v2.0.

## Getting started

First, install [swagger-express-ts](https://www.npmjs.com/package/swagger-express-ts).

```sh
npm install swagger-express-ts --save
```

and [init tsconfig.json](./wiki/installation.md)

## The Basics

In the examples below, we use [inversify-express-utils](https://www.npmjs.com/package/inversify-express-utils). inversify-express-utils is not required to work with swagger-express-ts.

### Step 1: configure express

```ts
import * as bodyParser from "body-parser";
import * as express from "express";
import "reflect-metadata";
import { Container } from "inversify";
import { interfaces, InversifyExpressServer, TYPE } from "inversify-express-utils";
import { VersionController } from "./version/version.controller";
import * as swagger from "swagger-express-ts";
import { SwaggerDefinitionConstant } from "swagger-express-ts";
const config = require ( "../config.json" );

// set up container
const container = new Container ();

// note that you *must* bind your controllers to Controller
container.bind ( TYPE.Controller )
.to( VersionController ).inSingletonScope().whenTargetNamed( VersionController.TARGET_NAME );

// create server
const server = new InversifyExpressServer ( container );

server.setConfig( ( app : any ) => {
app.use( '/api-docs/swagger' , express.static( 'swagger' ) );
app.use( '/api-docs/swagger/assets' , express.static( 'node_modules/swagger-ui-dist' ) );
app.use( bodyParser.json() );
app.use( swagger.express(
{
definition : {
info : {
title : "My api" ,
version : "1.0"
} ,
externalDocs : {
url : "My url"
}
// Models can be defined here
}
}
) );
} );

server.setErrorConfig( ( app : any ) => {
app.use( ( err : Error , request : express.Request , response : express.Response , next : express.NextFunction ) => {
console.error( err.stack );
response.status( 500 ).send( "Something broke!" );
} );
} );

const app = server.build();

app.listen( config.port );
console.info( "Server is listening on port : " + config.port );

```

### Step 2: Decorate your models

```ts
@ApiModel( {
description : "Version description" ,
name : "Version"
} )
export class VersionModel {

@ApiModelProperty( {
description : "Id of version" ,
required : true,
example: ['123456789']
} )
id : number;

@ApiModelProperty( {
description : "" ,
required : true
} )
name : string;

@ApiModelProperty( {
description : "Description of version" ,
required : true
} )
description : string;
}
```

### Step 3: Decorate your controllers

```ts
@ApiPath({
path: "/versions",
name: "Version",
security: { basicAuth: [] }
})
@controller("/versions")
@injectable()
export class VersionController implements interfaces.Controller {
public static TARGET_NAME: string = "VersionController";

private data = [{
id: "1",
name: "Version 1",
description: "Description Version 1",
version: "1.0.0"
},
{
id: "2",
name: "Version 2",
description: "Description Version 2",
version: "2.0.0"
}];

@ApiOperationGet({
description: "Get versions objects list",
summary: "Get versions list",
responses: {
200: { description: "Success", type: SwaggerDefinitionConstant.Response.Type.ARRAY, model: "Version" }
},
security: {
apiKeyHeader: []
}
})
@httpGet("/")
public getVersions(request: express.Request, response: express.Response, next: express.NextFunction): void {
response.json(this.data);
}

@ApiOperationPost({
description: "Post version object",
summary: "Post new version",
parameters: {
body: { description: "New version", required: true, model: "Version" }
},
responses: {
200: { description: "Success" },
400: { description: "Parameters fail" }
}
})
@httpPost("/")
public postVersion(request: express.Request, response: express.Response, next: express.NextFunction): void {
if (!request.body) {
return response.status(400).end();
}
this.data.push(request.body);
response.json(request.body);
}

}
```

### Step 4: Test

Start your server and test on url : /api-docs/swagger.json

## Extra

### Serve swagger-ui in your API

You can serve swagger.json and swagger-ui in your API.

```sh
npm install swagger-ui-dist --save
```

Create index.html in new directory "swagger".

```html


Swagger UI





html {
box-sizing: border-box;
overflow: -moz-scrollbars-vertical;
overflow-y: scroll;
}

*,
*:before,
*:after {
box-sizing: inherit;
}

body {
margin: 0;
background: #fafafa;
}
















window.onload = function () {

// Build a system
const ui = SwaggerUIBundle ({
url: "/api-docs/swagger.json",
dom_id: '#swagger-ui',
deepLinking: true,
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl
],
layout: "StandaloneLayout",
validatorUrl: null
});

window.ui = ui
}

```

Configure your server like that.

```ts
app.use( '/api-docs/swagger', express.static( 'swagger' ) );
app.use( '/api-docs/swagger/assets', express.static( 'node_modules/swagger-ui-dist' ) );
```

Test it on url "/api-docs/swagger".

![](./wiki/img/swagger-ui.png)

## Project example

You can quickly test swagger-express-ts with the project example [example-swagger-express-ts](https://github.com/olivierlsc/example-swagger-express-ts).

## Features and API

- [Installation](./wiki/installation.md)
- [Configuration](./wiki/configuration.md)
- [@ApiModel](./wiki/api-model.decorator.md)
- [@ApiModelProperty](./wiki/api-model-property.decorator.md)
- [@ApiPath](./wiki/api-path.decorator.md)
- [@ApiOperationGet](./wiki/api-operation-get.decorator.md)
- [@ApiOperationPost](./wiki/api-operation-post.decorator.md)
- [@ApiOperationPut](./wiki/api-operation-put.decorator.md)
- [@ApiOperationPatch](./wiki/api-operation-patch.decorator.md)
- [@ApiOperationDelete](./wiki/api-operation-delete.decorator.md)

## For any questions, suggestions, or feature requests

[Please file an issue](https://github.com/olivierlsc/swagger-express-ts/issues)!

## Help wanted

swagger-express-ts wants additional maintainers! To maintain and continue to develop this young library, [Please post in this issue](https://github.com/olivierlsc/swagger-express-ts/issues/34).