npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

api-nexus

v1.0.10

Published

Generation of API documentation for the GraphQl and Rest API

Downloads

142

Readme

api-nexus

npm

npm

GitHub

Overview

Api-nexus

api-nexus is a powerful tool for effortlessly generating comprehensive API documentation for both RESTful and GraphQL APIs. Whether you are building REST APIs or GraphQL schemas, this tool streamlines the documentation process, ensuring clarity and consistency.

Required Node Version => 16.0.0

Features

  • Automatic Documentation Generation: Easily generate API documentation based on your RESTful endpoints and GraphQL schemas.

  • Separate REST and GraphQL Documentation: Create distinct documents for RESTful APIs and GraphQL APIs.

  • Developer-Friendly Markdown Format: The generated documentation is presented in Markdown format, making it easy to read and edit.

  • Customization Options: Customize the appearance and content of your API documentation to meet your project's specific needs.

  • Interactive GraphQL Playground: Include an interactive GraphQL Playground for users to experiment with queries.

Documentation View

1. Getting Started

Step 1: Install api-nexus

  • Use the following command to install the api-nexus package in your project:
    
    > npm install -g api-nexus
                OR
    > npm install api-nexus
    

Step 2: Create a Config.yml File

  • Create a config.yml file in the root directory of your project. For an example configuration, refer to the [ config.yml Example here ]

Step 3: Set Environment Variables

  • Create a .env file in the project root directory and export the following environment variables:

    DOC_USER=test
    DOC_PASSWORD=test
    DOC_ENV=Development
    DOC_PORT=3001

Explanation:

  • If authentication is defined in your config.yml, provide the following environment variables:
    • DOC_USER=test
    • DOC_PASSWORD=test
  • The default server port is 3001. If you want to use a different port, set it with the DOC_PORT environment variable:
    • DOC_PORT=4000
  • Add the environment for which you want to create the documentation:
    • DOC_ENV=Development

Step 4: Update Package.json

  • Add the following command in your package.json to create the api documentation:
    "scripts": {
        "build-api-documentation": "npm explore api-nexus -- npm run build-api-documentation",
        "start": "node app.js"
    }

Step 5: Generate Documentation

  • Run the following command to generate the documentation files:
    > npm run build-api-documentation

Step 6: Verify Generated Files

  • After running the command, a doc folder will be created in the root directory with the following structure:

        doc
        ├── build
        ├── dist
        ├── graph
        │ ├── introspection.json
        │ └── graphMetaData.json
        │
        └── rest
            └── restMetaData.json
  • Note: These files are auto-generated, and renaming them may cause issues in document generation.You can also create this folder structure in the root project directory manual to run the document.

  • [Introspection JSON Example here]

  • [graphMetaData JSON Example here]

  • [restMetaData JSON Example here]

Step 7: Include Code Lines in Your Project

  • Include the following code lines in your project to enable the documentation:

    const express = require("express");
    const app = express();
    const path = require("path");
    
    # Include these lines of code
    const documentApi = require(path.join(__dirname,  "doc",  "build",  "server.cjs"));
    documentApi('/api/my-app/document')
    
    app.get("/health",  async (req, res) => {
        res.send("server is up");
    });
    
    app.use((err, req, res, next) => {
        console.error(err.stack);
        res.status(500).send("Something went wrong!");
    });
    
    const PORT = process.env.PORT || 3000;
    
    app.listen(PORT, () => {
        console.log(`Server is running on port ${PORT}`);
    });
  • Note : Adjust the path variable to set the base path at which your document will be visible. For example, /api/document , /api-project/document, etc.

Step 8: Access Document Server

  • You can access the document server at the following URL with the specified base path:

    >`domain:3001/api/my-app/document`
  • Note: If you have set the port to 4000, the URL will be accessible at domain:4000/api/my-app/document.

2. Getting Started With Docker & Nginx

  • Steps to setup through docker & nginx to run both ports on your domain

    Step 1: Create a Dockerfile

    • Create a docker file in the project root directory

    Step 2: Docker Configuration

    • Add the below configuratio to the docker file

      FROM node:16
      # Set the working directory
      WORKDIR /app
      # Copy only the package.json and package-lock.json to leverage Docker cache
      COPY package*.json ./
      # Install app dependencies
      RUN npm install
      # Build the API documentation (if needed)
      RUN npm run build-api-documentation
      # Copy the rest of the application code
      COPY .  .
      # Expose the necessary ports
      EXPOSE 3000
      EXPOSE 3001
      # Run the application
      CMD ["npm", "start"]

    Step 3: Nginx Setup

    • Create the below setup for the server proxy using Nginx:

      server {
          server_name my-domain;
          client_max_body_size 1024m;
          location /api/document {
          proxy_pass http://my-domain:3004/api/document;
          proxy_http_version 1.1;
          proxy_set_header Host $http_host;
          proxy_set_header X-Real-IP $remote_addr;
          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
          proxy_set_header X-Forwarded-Proto $scheme;
          proxy_set_header Upgrade $http_upgrade;
          proxy_set_header Connection "upgrade";
      }
      
      location / {
          proxy_pass http://my-domain:3002;
          proxy_http_version 1.1;
          proxy_set_header Host $http_host;
          proxy_set_header X-Real-IP $remote_addr;
          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
          proxy_set_header X-Forwarded-Proto $scheme;
          proxy_set_header Upgrade $http_upgrade;
          proxy_set_header Connection "upgrade";
          }
      }
    • Explanation

      • Let's consider you set the base URL as /api/document using the documentApi('/api/document') configuration in your application.

      • Now, in the Nginx setup, the location /api/document block is configured to handle requests for /api/document. This block uses proxy_pass to direct these requests to the document API server, which is assumed to be running on port 3001 and mapped to port 3004 using the Docker command:

        > sudo docker run -it -p 3002:3000 -p 3004:3001 api-nexus
      • So, the proxy_pass in the Nginx configuration becomes http://my-domain/api/document.You can handle other base URLs in a similar way by creating additional location blocks in the Nginx configuration, allowing you to route different parts of your application to various backend servers based on your requirements. Adjust the port numbers and base URLs accordingly for your specific setup.

3. Getting Started With Http-Proxies

  • If you prefer not to use Nginx for proxying, follow the steps below to serve the document using the HTTP proxy instead.

    const express = require("express");
    const app = express();
    const path = require("path");
    const { createProxyMiddleware  }  =  require("http-proxy-middleware");
    
    # Include the API Nexus documentation server (Load the .cjs as it is supported in both commonJs & ES)
    # If you are using ES module, you  need to use the import statement instead of the require.
    # import path from 'path';
    # import documentApi from './doc/build/server.cjs';
    
    const documentApi = require(path.join(__dirname,  "doc",  "build",  "server.cjs"));
    documentApi('/api/document');
    
    # Create a proxy middleware for the "/api/document" route
    const documentProxy = createProxyMiddleware({
    	target:  "http://domain:3001",  //  Replace  with  the  actual  destination  server  URL
    	changeOrigin: true,
    });
    
    # Use the proxy middleware for the "/api/document" route
    app.use("/api/document",  documentProxy);
    
    app.get("/health",  async (req, res) => {
    	res.send("server is up");
    });
    
    app.use((err, req, res, next) => {
    	console.error(err.stack);
    	res.status(500).send("Something went wrong!");
    });
    
    const PORT = process.env.PORT || 3000;
    app.listen(PORT, () => {
    	console.log(`Server is running on port ${PORT}`);
    });
  • With the above http proxy setup you can access the api-documentation at domain:3000/api/document.With the above setup you can access both the API with the same port.

Config.yml Options

| Variable | Default | Description | |-----------------------------|-----------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------| | | API Nexus | | | env | ${DOC_ENV} | Specify the environment for documentation (Development, Qa, Staging, Production) | | includeExample | true | Include example (true/false) [default=true] | | | Authentication | | | documentUser | ${DOC_USER} | Default user is - [documentUser=test] | | documentPassword | ${DOC_PASSWORD} | Default password is - [documentPassword=test@123] | | | Info | | | title | Sample | Title for the main page [default=Sample] | | logo | Logo | URL for the logo image [default=Logo] | | includeDocumentType | both | Include document type (graph, rest, both) [default=both] | | introduction | Welcome to our comprehensive guide on Application Programming Interfaces (APIs). ... | Introduction for the main page | | graphDescription | Welcome to the GraphQL API Overview, your gateway to the future of data querying ... | Description for GraphQL API [default=some description] | | restDescription | Welcome to the REST API Overview, your comprehensive resource for understanding and working ... | Description for REST API [default=some description] | | | REST | | | title | REST | [default=Sample] | | version | 2.0.0 | [default=1.0.0] | | description | This comprehensive reference provides detailed information on the GraphQL types, ... | Description for REST API [default=Some description] | | | Servers | | | url | https://sample-dev.com/api/rest | Server URL for REST API | | env | Development | Environment for the server | | headers | Authorization: <YOUR_TOKEN_HERE> | Headers for the server | | | GraphQL | | | title | GraphQL | [default=Sample] | | version | 2.1.0 | [default=1.0.0] | | description | This comprehensive reference provides detailed information on the GraphQL types, ... | Description for GraphQL API [default=Some description] | | | GraphQL Introspection | | | url | https://sample-dev.com/api/graphql | URL for GraphQL introspection [Make sure it is accessible and allowed to access] | | overWriteEachTime | false | Overwrite introspection each time [default=false] | | | GraphQL Servers | | | url | https://sample-dev.com/api/graphql/dev | Server URL for GraphQL API (Development) | | env | Development | Environment for the server | | headers | Authorization: <YOUR_TOKEN_HERE>, Content-Type: "application/json" | Headers for the server (Development) |

Note: You can replace <YOUR_TOKEN_HERE> with the actual token. The URLs and other values should be adjusted based on your specific configuration.