I have an existing NodeJS API and I want to add Swagger-UI to it. This makes the API look much more professional very quickly.
Before you continue, you may want to view a working copy of this Swagger UI I've built in this article at https://seans-typescript-nodejs-crud.herokuapp.com/swagger/
Lets Start Coding
- Install swagger-ui-express in your project.
npm -i swagger-ui-express --save
package.json should now contain a reference to
swagger-ui-express and since I used the
--save option, it will also be available when started with production settings. Use
--save-dev if you prefer it to be only available when you run it in development mode.
2. Open your
app.ts or whatever you called your main NodeJS API script and add
import swaggerUi from ‘swagger-ui-express’ to the top.
3. Create a new file called
swagger.json and paste some default text into it.
4. Now also add
import * as swaggerDocument from ‘./swagger.json’ to the top of your main NodeJS API script. This creates a reference to the
swagger.json file you just created in step 3.
NOTE TypeScript specific issue : At some point, if you get an error indicating inability to import JSON files, then you can add
5. Now create a new route in your
app.ts to reference the swagger-ui. Add the line
this.httpServer.use(‘/swagger’, swaggerUi.serve, swaggerUi.setup(swaggerDocument));
My full final
app.ts code looks like this below.
6. Now you can start your dev server
npm run dev
Visit the URL http://localhost:3000/swagger and you now have Swagger-UI in your existing NodeJS API.
Now your NodeJS environment is probably different than mine, so I have also provided this full completed code setup on GitHub at https://github.com/Sean-Bradley/Seans-TypeScript-NodeJS-CRUD-REST-API-Boilerplate
A minimal and easy to follow example of what you need to create a CRUD style API in NodeJs using TypeScript …
After setting up your beginning
swagger.json file as described above in step 2, you will need to go through your API endpoints one by one and create the OpenAPI3.0 spec for each endpoint you want documented. I recommend watching my video on setting all this up, so that you can see the various steps and how I resolve all the problems along the way.
The Full swagger.json as used in my video tutorial
definitions at the bottom,
and then further up I have
paths which further describes the API URLs, their parameters, HTTP methods, variables and HTTP status codes.