Refactoring into RESTful API

Aditya Naik
Nomads Of Code
Published in
3 min readJul 7, 2020
Photo by Urip Dunker on Unsplash

This is Part 7 of multi-part series on ExpressJS.

You can find Part 1 here. It talks about building a basic express api and setting up mocha for testing.

You can find Part 2 here. It talks about setting up PostgreSQL, sequelize for connecting express api with databases.

You can find Part 3 here. It talks about setting up associations (has many as well as belongs to) between two models.

You can find Part 4 here. It talks about setting up user authentication based on email and password.

You can find Part 5 here. It talks about using json web token to protect a route.

You can find Part 6 here. It talks about advanced associations (many-to-many-through) and through/junction tables.

What is restful API

REST stands for Representational State Transfer, a term coined by Roy Fielding in 2000. It is an architecture style for designing loosely coupled applications over HTTP, that is often used in the development of web services. REST does not enforce any rule regarding how it should be implemented at lower level, it just put high level design guidelines and leave you to think of your own implementation.

Refactoring our API to make it RESTful

We will restructure our controllers and use only index and show actions, as they are the only relevant actions applicable in our case.

We will do the following —

  • Extract the sequelize queries in a separate folder
  • Normalize our controllers and use the standard restful method names

Extract sequelize queries

Create a queries folder inside models folder.

Create posts.js and users.js to place relevant queries in appropriate file.

Nothing fancy here, just extracting out queries from our controllers and handling them here in a separate place.

Also add index.js to collect the queries and make it easier to import in controller.

Now to use them in controllers.

Update controllers

Now that the queries are hidden out of the sight, our controllers are going to be really slim.

Pretty structured now!

Update routes to user the new fancy controllers!

Make sure all the tests are still going green.

Next article will talk about adding unit tests for controllers and models.

Craft Academy is a Tech Education Provider that aims to bring new talent to the market and help to solve the shortage of tech workers. We are founded on the belief that modern development standards, agile methodologies, and business skills are fundamental for IT professionals.

Our primary service is a 12-week coding bootcamp designed to provide individuals with a foundation of skills that allows them to enter the industry as junior developers.

With that foundation, our learners find employment in various industries or start their own businesses that bring new innovations to the market.

Would you like to know more about what we do? Follow us here on Medium, Facebook, Twitter or visit our website.

--

--