List All REST Endpoints built using Express or Restify4 min read

List All REST Endpoints built using Express or Restify

In this post, we will list out all the routes that are configured in an Express js app or a Restify app. We will simply look up a server object that stores the end points and list them out.

The output would be something like

Screen Shot 2014-05-05 at 8.00.46 pmYou can checkout the runnable here. The source code can be found here.

So, lets get started.

The entire post can be summarized into the below table. The Routes object is the variable that stores the list of routes those are configured.

Server Side Component Routes Object
Express 3.x   app.routes
Express 4.x   app._router.stack
Restify   server.router.mounts

You can run a console.log(obj)  or console.log(JSON.stringify(obj)) on above objects to see their guts in their respective environments.

Let’s get building. First we will create an app using Restify. I will ‘borrow’ my own code from this post. And build a simple Restify server.

Create a new folder named listMyAPI. The run npm init to initialize a new Node project. Fill up the details accordingly. Then we will add a few dependencies. Run

npm i express --save

npm i restify --save

npm i mongojs --save

npm i cli-table

cli-table dependency is to print the routes table in the console.

Next, create a new file at the project root named restify.js. And copy the below contents to it

This is a simple rest server that will hit the DB and fetch some data. On line 91, we are calling another js file named document.js and passing in the routes object, which we will create now. If you log server.router.mounts to console you would see

Sweet right? Now, create a new file named document.js. This file is only for the demo to pretty print a table at the terminal/prompt. Update document.js with

Now run

node restify.js 

and you should see

Screen Shot 2014-05-05 at 8.54.45 pm

Next, lets try the same with Express js. Create a new file at the project root named express.js. And dump the below server code

If you console log the app._router.stack object, you would see

All the data we need. Run

node express.js 

and you should see

Screen Shot 2014-05-05 at 9.05.46 pm

For a more real time usage, you can define an endpoint in you app like

and then dispatch the routes object to an api.html or an api.jade view iterate and build a table. Something like

Simple and Helpful.

Thanks for reading! Do comment.