Building an API framework in ExpressJS and NodeJS & now PHP

Robert Coster
2 min readOct 24, 2019

There are many times in projects using React and Vue when you need a an API to interact and store data. The so-called Jamstack appears to have gained a significant momentum over the traditional CMS supplied view layer ( a really good thing IMHO).

To help with this I’ve started developing a new, easy to setup, easy to configure API framework at https://github.com/signalfire/xapi-node. This framework — based on ExpressJS and NodeJS is designed around a single regex based routes JS file. This file is designed thus…

const Joi = require('joi'); module.exports = {
routes: [{
url: { pattern: /^\/$/ },
secure: true,
roles: [],
method: 'GET',
rules: {},
controller: { path: './controllers/home.js' },
}]
}

In this routes file you have the url pattern — which is a regex. Then you have the secure (true|false) property. Setting this to true will kick in some custom middleware which checks the Authorization header for a bearer token (JWT). If set to secure and no token, or invalid or expired token then you are blocked with an HTTP status code 403.

The roles array allows you to specify a series of roles that must be present in any JWT token in order to allow access to the route thereby further refining who can access a route.

You will notice a call to Joi — a decent validation framework for Node. Declaring rules will ensure that before hitting the controller the data you’ve provided is validated. Not valid, then you don’t hit the controller. Controllers are code that is executed for routes.

I’ve started developing and added to this framework some generic controllers to handle many of the functions you need with an API. Currently we have a list controller. This will, when provided the model name (and any filtering options) return a paginated result-set for the provided model. In addition we also have a get controller that will find a single record based on a querystring value.

Further to these controllers we also have a final 2 that provide a generic function. Register and Login. These controllers will allow user registration and login based on the (Sequelize) user model found in the models folder.

This is very much a work in progress, testing (loads) and further refactoring to do, but so far, so good. I will update this article / add a new one when complete.

P.S I will be creating a vanilla PHP version of this as well for Node-phobes.

--

--

Robert Coster

Web Developer using #php, #node and other open source web platforms. i like to say stuff on politics as well.