Building REST API using Koa JS and MongoDB

Kawsikan K.
4 min readMay 2, 2021

Koa Js is a node framework that is used to build server-side web applications. When comparing with Express Js, Koa Js is minimal and lightweight.

In this blog, we will build a small Rest API using Koa Js with all the CRUD operations and we will connect it to MongoDB.

First, you need to create a directory and npm init the directory.

cd directory

npm init

Then install koa and save it as a development dependency.

npm i koa — save-dev

Install koa router to create routes.

npm i @koa/router

Install body-parser to parse your requests.

npm i koa-bodyparser

Installing UUID to create a unique id.

npm install uuid

Inside the main directory create a file called index.js.

const Koa = require('koa');
const bodyParser = require('koa-bodyparser');

const app = new Koa();

app.use(bodyParser());

app.listen(3000);
console.log('Application is running on port 3000');

Now you should be able to start the server by giving the command :

node index.js

Now in order to connect to MongoDB, first you need to have MongoDB installed in your system and running instance.

Then you need to install the MongoDB driver into your project directory in order to connect to MongoDB.

npm install mongodb

Then create a directory named dal inside the main project directory which, acts as a data access layer and provides simplified access to data stored in storage.

Inside the dal directory create a file called index.js and include the following code.

const {MongoClient} = require('mongodb');

const client = new MongoClient('mongodb://localhost:27017/posts', {
useNewUrlParser: true,
useUnifiedTopology: true
});
// connecting mongo db
client.connect(err => {
if (err) {
console.error(err);
process.exit(-1);
}
console.log('Successfully connected to mongodb')
})
module.exports = client;

Create another file named posts.dao.js inside the dal directory and include the below code.

const posts = require('./').db('posts').collection('posts');

const save = async ({id, name, description, postedDate}) => {
const result = await posts.insertOne({id, name, description, postedDate});
return result.ops[0];
};

const getAll = async () => {
const cursor = await posts.find();
return cursor.toArray();
};

const getById = async id => {
return await posts.findOne({id});
};

const removeById = async id => {
await posts.deleteOne({id});
};

const update = async (id, {name, description, postedDate}) => {
const result = await posts.replaceOne({id}, {id, name, description, postedDate});
console.log(result);
return result.ops[0];
};


module.exports = {getAll, getById, removeById, save, update};

Now create another folder called api inside the main directory. Inside the api folder create a file called posts.api.js. and include the following code.

const UUID = require('uuid');
const {getAll, getById, removeById, save, update} = require('../dal/posts.dao')

const createPost = async ({name, description}) => {
let post = {
id: UUID.v4(),
name,
description,
postedDate: new Date()
}
return await save(post);
};
let getPosts = async () => {
return await getAll();
};
let getPost = async id => {
return await getById(id);
};

let deletePost = async id => {
return await removeById(id);
};
let updatePost = async (id, {name, description, postedDate}) => {
return await update(id, {id, name, description, postedDate});
};

module.exports = {
createPost,
deletePost,
getPosts,
getPost,
updatePost
};

Now we need to create routes for our application. Create another folder called routes inside the main directory and create a file posts.routes.js and include the below code.

const Router = require("@koa/router");
const {createPost, deletePost, getPosts, getPost, updatePost} = require('../api/posts.api')

const router = new Router({prefix: '/posts'});

router.get('/', async ctx => {
ctx.body = await getPosts();
});

router.post('/', async ctx => {
let post = ctx.request.body;
post = await createPost(post);
ctx.response.status = 201;
ctx.body = post;
});
router.get('/:id', async ctx => {
const id = ctx.params.id;
ctx.body = await getPost(id);
});

router.put('/:id', async ctx => {
const id = ctx.params.id;
let post = ctx.request.body;
post = await updatePost(id, post);
ctx.body = post;
});

router.del('/:id', async ctx => {
const id = ctx.params.id;
ctx.response.status = 204;
ctx.body = await deletePost(id);
});

module.exports = router;

Now update index.js in order to import files and set all the routes.

const Koa = require('koa');
const PostsRoutes = require('./routes/post.routes');
const bodyParser = require('koa-bodyparser');

require('./dal')

const app = new Koa();
app.use(bodyParser());

app.use(PostsRoutes.routes())
.use(PostsRoutes.allowedMethods());


app.listen(3000);
console.log('Application is running on port 3000');

Now before you run your application make sure MongoDB is started on your local machine.

node index.js

Now when you can use a tool like Postman to test the API.

For GET request: http://localhost:3000/posts

For POST request: http://localhost:3000/posts

{
"name" : "Peter",
"description" : "My fist Post"
}

For DELETE and PUT requests, you need to use UUID instead of the id created by MongoDB.

For DELETE request : http://localhost:3000/posts/{id}

For PUT request : http://localhost:3000/posts/{id}

{
"name" : "Peter",
"description" : "My fist Post",
"postedDate" copy & paste the date
}

It should work .

So, that is all for this article and you can follow me if you want to get notification about my technical blogs.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Kawsikan K.
Kawsikan K.

Written by Kawsikan K.

I am an undergraduate student following software engineering degree. I am interested in learning new technologies and I love writing.

No responses yet

Write a response