Creating the olee-express-api-doc
Library
Step 1.1: Set Up the Library Project
- Create the Library Directory:
mkdir olee-redoc-api-doc
cd olee-redoc-api-doc
Initialize the Project:
npm init -y
add keyword and description
{
"name": "olee-redoc-api-doc",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"express",
"swagger",
"redoc",
"api-docs",
"api-documentation",
"swagger-ui",
"redoc-documentation",
"expressjs",
"nodejs",
"swagger-jsdoc",
"swagger-express",
"swagger-node",
"swagger-redoc",
"nodejs-library",
"express-middleware",
"swagger-api",
"rest-api-docs"
],
"author": "olee ahmmed",
"license": "ISC",
"description": "`olee-express-api-doc` is a simple and configurable library for setting up automatic API documentation in Express.js applications using Swagger and Redoc. This library allows developers to easily generate and serve both Swagger UI and Redoc documentation with minimal configuration. Just import the library, call the setup function, and your API documentation is ready to go. Perfect for Node.js backend developers looking to streamline their API documentation process."
}
Install Dependencies:
npm install express swagger-jsdoc swagger-ui-express dotenv
We won’t install Redoc as a dependency because we’ll use the hosted version of Redoc from a CDN.
Step 1.2: Create the Library Code
- Create
index.js
:This will be the main file for your library.
const swaggerJsdoc = require('swagger-jsdoc');
const swaggerUi = require('swagger-ui-express');
const path = require('path');
const express = require('express');
require('dotenv').config();
function setupDocs(app) {
const swaggerDefinition = {
openapi: '3.0.0',
info: {
title: process.env.API_TITLE || 'API Documentation',
version: process.env.API_VERSION || '1.0.0',
description: process.env.API_DESCRIPTION || 'API documentation for the Express app',
},
servers: [
{
url: process.env.SERVER_URL || 'http://localhost:3000',
},
],
};
const options = {
swaggerDefinition,
apis: [process.env.APIS_PATH || './routes/*.js'], // Default location of route files
};
const swaggerSpec = swaggerJsdoc(options);
// Serve Swagger UI
app.use(process.env.SWAGGER_DOCS_PATH || '/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));
// Serve Redoc documentation
app.get(process.env.REDOC_PATH || '/redoc', (req, res) => {
res.sendFile(path.join(__dirname, 'redoc.html'));
});
// Serve the swagger.json file that Redoc will use
app.get('/swagger.json', (req, res) => {
res.setHeader('Content-Type', 'application/json');
res.send(swaggerSpec);
});
}
module.exports = setupDocs;
This code does the following:
setupDocs(app)
: A function that sets up Swagger UI and Redoc based on environment variables.- Environment Variables: Allows customization for title, version, description, server URL, API paths, and documentation paths.
Create the redoc.html
File:
This file serves the Redoc documentation page.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>API Documentation</title>
<!-- Load Redoc -->
<script src="https://cdn.redoc.ly/redoc/latest/bundles/redoc.standalone.js"></script>
</head>
<body>
<redoc spec-url="/swagger.json"></redoc>
</body>
</html>
-
- Redoc: We are loading Redoc from a CDN, which will render the API documentation using the
swagger.json
file.
- Redoc: We are loading Redoc from a CDN, which will render the API documentation using the
.npmignore
for olee-redoc-api-doc
# Node modules directory
node_modules/
# Logs
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# OS-specific files
.DS_Store
Thumbs.db
# IDE/editor directories
.vscode/
.idea/
# Test and coverage directories
test/
coverage/
# Build output (if applicable)
dist/
build/
# Documentation (if not needed in the package)
docs/
# Examples and demo files (if not included)
examples/
demo/
# Local environment files
.env
# Git files
.git/
.gitignore
.gitattributes
# Other
*.md
Prepare for Publishing
Add a few more files to prepare for publishing on npm:
- README.md – To describe how to use your library.
- .gitignore – To ignore
node_modules
and other unnecessary files.
Step 1.3: Publish the Library to npm
- Login to npm:
npm login
Publish Your Package:
npm publish
Part 2: Using the olee-express-api-doc
Library in an Express.js Project
Step 2.1: Create a New Express Project
- Create the Project Directory:
mkdir express-project
cd express-project
Initialize the Project:
npm init -y
Install Express and Your Library:
npm install express olee-redoc-api-doc
Step 2.2: Set Up Environment Variables
- Create a
.env
File:
touch .env
Add Environment Variables:
API_TITLE=My Express API
API_VERSION=1.0.0
API_DESCRIPTION=API documentation for my Express app
SERVER_URL=http://localhost:3000
APIS_PATH=./routes/*.js
SWAGGER_DOCS_PATH=/api-docs
REDOC_PATH=/redoc
- These variables will be used by the
setupDocs
function to customize your API documentation.
Step 2.3: Create an Express Server and Use the Library
- Create
index.js
:This will be the entry point of your Express application.
const express = require('express');
const setupDocs = require('olee-redoc-api-doc'); // Import your library
const app = express();
app.use(express.json());
// Setup API documentation using your library
setupDocs(app);
// Example route
app.get('/api/v1/users', (req, res) => {
res.json([{ id: 1, name: 'John Doe' }]);
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
- The
setupDocs(app)
function automatically sets up Swagger UI and Redoc based on the configuration provided in the.env
file.
Step 2.4: Create a Route File with Swagger Comments
- Create a
routes
Folder and ausers.js
File:
mkdir routes
touch routes/users.js
Add Code to users.js
:
/**
* @swagger
* /api/v1/users:
* get:
* summary: Retrieve a list of users
* responses:
* 200:
* description: A list of users
* content:
* application/json:
* schema:
* type: array
* items:
* type: object
* properties:
* id:
* type: integer
* description: The user ID
* example: 1
* name:
* type: string
* description: The user's name
* example: John Doe
*/
const express = require('express');
const router = express.Router();
router.get('/users', (req, res) => {
res.json([{ id: 1, name: 'John Doe' }]);
});
module.exports = router;
Update index.js
to Include the Route:
const express = require('express');
const setupDocs = require('olee-express-api-doc'); // Import your library
const userRoutes = require('./routes/users'); // Import the routes
const app = express();
app.use(express.json());
// Setup API documentation using your library
setupDocs(app);
// Use the routes
app.use('/api/v1', userRoutes);
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Step 2.5: Run the Server and View Documentation
- Start the Express Server:
node index.js
Access Your Documentation:
- Swagger UI: Visit
http://localhost:3000/api-docs
. - Redoc: Visit
http://localhost:3000/redoc
.
To help developers use the olee-redoc-api-doc
library effectively, here are some additional resources and files you might include:
Project Structure
File/Directory | Purpose |
---|---|
README.md | Provides a detailed guide on installation, usage, and configuration. |
.env | Contains environment variables for configuration. |
setupDocs.js | Script for initializing the API documentation setup. |
example-routes.js | Example route file demonstrating how to use Swagger comments. |
docs/ | Directory for additional documentation or example files. |
LICENSE | License information for the library. |
.npmignore | Specifies files to be excluded from the npm package. |
Example Files
README.md
# olee-redoc-api-doc
`olee-redoc-api-doc` is a library for setting up automatic API documentation in Express.js applications using Swagger and Redoc.
## Installation
```bash
npm install olee-redoc-api-doc
Usage
Create setupDocs.js
:
const express = require('express');
const setupDocs = require('olee-redoc-api-doc');
require('dotenv').config();
const app = express();
setupDocs(app);
app.get('/users', (req, res) => {
res.json([{ id: 1, name: 'John Doe' }]);
});
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
Create .env
:
API_TITLE=My Express API
API_VERSION=1.0.0
API_DESCRIPTION=API documentation for my Express app
SERVER_URL=http://localhost:3000
APIS_PATH=./routes/*.js
SWAGGER_DOCS_PATH=/api-docs
REDOC_PATH=/redoc
Example Route File
example-routes.js
/**
* @swagger
* /users:
* get:
* summary: Retrieve a list of users
* responses:
* 200:
* description: A list of users
* content:
* application/json:
* schema:
* type: array
* items:
* type: object
*/
app.get('/users', (req, res) => {
res.json([{ id: 1, name: 'John Doe' }]);
});
License
MIT
Contributing Guidelines
Include a CONTRIBUTING.md
file to guide developers on how to contribute to your library. This file should provide:
- Instructions for setting up a development environment
- Code style guidelines
- How to submit issues and pull requests
- Testing procedures
Example:
# Contributing to olee-redoc-api-doc
Thank you for your interest in contributing to `olee-redoc-api-doc`! We welcome contributions and feedback.
## Getting Started
1. **Fork the repository**: Create your own copy of the repository by forking it on GitHub.
2. **Clone your fork**: Clone your forked repository to your local machine.
```bash
git clone https://github.com/your-username/olee-redoc-api-doc.git
Install dependencies: Navigate to the project directory and install dependencies.
npm install
Make changes: Create a new branch for your changes.
git checkout -b feature/your-feature
Test your changes: Ensure that your changes do not break any existing functionality and that new features work as expected.
Commit and push: Commit your changes and push them to your fork.
git add .
git commit -m "Add feature XYZ"
git push origin feature/your-feature
Submit a pull request: Go to the original repository and submit a pull request from your branch.
Changelog
A CHANGELOG.md
file helps users track changes across versions of your library. It should list major updates, bug fixes, and improvements.
Example:
# Changelog
## [1.1.0] - 2024-09-01
### Added
- Support for custom Redoc configuration
- New environment variable for API title
### Fixed
- Minor bugs in Swagger documentation generation
## [1.0.0] - 2024-08-01
### Initial Release
- Basic functionality for setting up Swagger and Redoc documentation
Examples Directory
Provide practical examples of how to use your library in a examples/
directory. Include sample code and configurations.
# Examples
## Basic Usage
```javascript
const express = require('express');
const setupDocs = require('olee-redoc-api-doc');
require('dotenv').config();
const app = express();
// Set up API documentation
setupDocs(app);
// Define your routes
app.get('/users', (req, res) => {
res.json([{ id: 1, name: 'John Doe' }]);
});
// Start the server
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
Advanced Configuration
const express = require('express');
const setupDocs = require('olee-redoc-api-doc');
require('dotenv').config();
const app = express();
// Set up API documentation with custom settings
setupDocs(app, {
title: 'Advanced API',
version: '2.0.0',
description: 'Advanced API documentation',
serverUrl: 'http://localhost:3000',
apis: ['./api/**/*.js'],
swaggerPath: '/docs',
redocPath: '/redoc'
});
// Define your routes
app.get('/items', (req, res) => {
res.json([{ id: 1, name: 'Item A' }]);
});
// Start the server
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
Test Cases
Include tests to ensure your library functions correctly. You can use a test/
directory with a testing framework like Jest or Mocha.
Example:
const request = require('supertest');
const express = require('express');
const setupDocs = require('olee-redoc-api-doc');
require('dotenv').config();
const app = express();
setupDocs(app);
describe('API Documentation', () => {
it('should return Swagger UI at /api-docs', async () => {
const res = await request(app).get('/api-docs');
expect(res.statusCode).toEqual(200);
});
it('should return Redoc at /redoc', async () => {
const res = await request(app).get('/redoc');
expect(res.statusCode).toEqual(200);
});
});
File and Directory
olee-redoc-api-doc/
├── examples/
│ └── basic-usage.js
│ └── advanced-configuration.js
├── src/
│ ├── index.js
│ └── setupDocs.js
├── test/
│ └── setupDocs.test.js
├── .env.example
├── .gitignore
├── .npmignore
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── CHANGELOG.md
├── README.md
├── package.json
└── package-lock.json
how update next time
1. Make Changes
Modify Code or Add Features:
- Edit the source files or add new features in your library as needed.
Update Documentation:
- Ensure that any changes are reflected in the
README.md
and any other documentation files.
2. Update Version Number
Follow Semantic Versioning (SemVer) guidelines for versioning your package. Update the version
field in your package.json
file.
Versioning Convention:
- Major: Breaking changes.
- Minor: New features in a backward-compatible manner.
- Patch: Backward-compatible bug fixes.
Example:
{
"name": "olee-redoc-api-doc",
"version": "1.1.0", // Update this as needed
...
}
Increment Version:
- Use the
npm version
command to update the version number automatically:
npm version major # For major updates
npm version minor # For minor updates
npm version patch # For patch updates
Update CHANGELOG.md
Document Changes:
- Maintain a
CHANGELOG.md
file to document all significant changes made in each version. This helps users understand what has changed in each release.
Example:
# Changelog
## [1.1.0] - 2024-09-01
### Added
- New configuration options for Swagger and Redoc setup.
- Additional examples in documentation.
### Fixed
- Resolved issues with Redoc path configuration.
## [1.0.0] - 2024-08-01
- Initial release.
4. Run Tests
Ensure Everything Works:
- Run any unit or integration tests to ensure that your changes don’t break existing functionality.
Example
npm test
5. Publish to NPM
Login to NPM:
- If you haven’t logged in, use
npm login
Publish the Package:
- Publish your updated package with:
npm publish
Verify Publication:
- Check your package on npmjs.com to ensure it is published correctly.
6. Communicate Changes
Notify Users:
- Inform users of significant updates, especially if they require action or involve breaking changes.