How to create an expressjs based RESTful API using express-ve package.

Merhawi Fissehaye
4 min readFeb 13, 2022

(Disclosure: I am the creator of express-ve)

I find expressjs to be a simple and straightforward framework to create a RESTful API. I mostly use mongoosejs to store my data in mongodb. To avoid repeating myself to create some things on my projects, I created express-ve as a simplifier to create routes, repositories and configurations easily.

Let’s go ahead create a simple blog api using express-ve. If you just want to checkout a demo project you can find it here.

First create your project folder and cd into it, I will call it expressive-blog. Also make sure mongodb is installed and running on your machine.

mkdir expressive-blog && cd expressive-blog

Initialize npm inside it, install express-ve and create your index.jsfile. I prefer to use yarn but you can use npm too. See the difference here.

yarn init -y
yarn add express-ve
touch index.js

Your files will now look something like this:

// index.js

require('dotenv').config()
const { createContainer } = require('../../../node-packages/node-ioc/index')

createContainer().then((container) => {
const { app } = container
app.listen(4040, () => {
console.log('Listening at port 4040')
})
})

// package.json


{
"name": "demo",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"dependencies": {
"dotenv": "^16.0.0",
"express-ve": "^0.0.31"
},
"scripts": {
"start": "nodemon index.js"
}
}

If you try to run the code by running yarn start or node index.js you will find out that it will throw error Mongo Error: Error: No db name provided. That’s because express-ve is trying to connect to a mongodb database and we haven’t told it what database name to use. It expects the database name as an evironment variable DB_NAME. Let’s try running it as DB_NAME=blogs node index.js.

I usually prefer to define my environment variables in a .env variable and use the dotenv package to load them. Run yarn add dotenv. Update index.js and add require('dotenv').config() at the top of it. You can also define your variables using config as explained here.

Routes

Let’s create our first route. First create a folder routes and create the files v1/index.js This will map to a route GET /v1 and put this code snippet in it.

module.exports = (container) => {
return {
route: (req, res) => {
return res.json({ message: 'Welcome to the API' })
}
}
}

Restart the server and go to localhost:4040/v1 . You should be able to see the Welcome message in the result. Should you want to add a prefix to all routes, you can add a configuration. Create a folder config at the root of your project and create a file named routes.js

module.exports = {
prefix: 'api'
}

This will tell express-ve to create all routes prefixed by api. Restart your server and go to localhost:4040/api/v1

Now let’s create a more complicated path. How expressi-ve maps the routes is specified here. Create a file on the path /api/v1/blog/__post.js. Note the double underscore before the method name POST. It will automatically map onto POST /api/v1/blog/ We can now send a post request to create a blog. Put the following code inside the file.

// /v1/blog__post.js
module.exports = (container) => {
return {
route: (req, res) => {
return res.status(401).json({ message: 'Blog has been created' })
}
}
}

Now before we start actually creating the blogs and seeing the result in the database, let’s create the model and schema. Create a folder named db at the root of your project.

// db/blog.js
module.exports = (mongoose) => {
const BlogSchema = new mongoose.Schema({
title: {type: String, required: true},
content: {type: String, required: true},
}, { timestamps: true })

mongoose.model('Blog', BlogSchema)
}

Wouldn’t it be awesome if we can get some methods by default like get, create, update and delete. express-ve allows you to add to the routes config resources. Let’s define a blog resource.

// config/routes.js
module.exports = {
prefix: 'api',
resources: ['v1/blog']
}

This will add all the routes GET v1/blog POST v1/blog PUT v1/blog/:blog DELETE v1/blog/:blog

Now when you check one of the endpoints above, you will get an Unauthorized result. express-ve expects you to explicitly allow access to models. They will be protected otherwise.

Now define a config/permissions.js at the root of your project and put the following content in it.

module.exports = {
blog: {
read: true,
write: true,
delete: false,
},
}

This explicitly states that we can read and write blogs but not delete. Delete the v1/blog__post.js that you created above. Now try to check the above routes again. Provide title and content to the body of the POST request, otherwise it will give validation errors.

In Part 2 we will see how to create repositories, configurations and how to use middlewares. Stay tuned. Thank you for trying express-ve If you have questions or suggestions, please leave me a message.

--

--

Merhawi Fissehaye

አሳቢና ጸሓፊ ነኝ። በተለይም ኃሳብ ከሰዎች ጋር ባለው ትስስርና እንዴት ከእውነታ ጋር መገናኘት እንደሚችል መመራመር እወዳለሁ። በጽሑፎቼም እነዚህን ግኝቶቼን አሰፍራለሁ።