Build your own REST API from scratch - Part 1




RESTful API is a key program interface that allows connectivity for endless amount of applications. 
I have actually published an article with a brief introduction to REST API which you can find in this blog post

In this article we are going to kick it up a notch and go step by step in building our own REST API from scratch. 

Choose your weapon...

For this task we are going to need the following:
  • nodeJS
  • npm
  • express
  • Visual Studio Code 

Create our project

First of all, I'm going to create my project folder, and open it in vs code.


Next, I will open a new terminal in VS Code and execute $npm init.





For this simple example we can leave everything at default and just hit Enter/return to finish our setup.

Next, I am going to install my dependencies by running $npm install.


Once the setup is finished, I am going to see my project folder populated with package.json, package-lock.json files, and the node_modules folder. which will contain my dependencies. 


Let's start writing our code...

I'm going to start by adding an index.js file to my project folder. In the below example, I'm explaining each line of code so we can be on the same page.

In the following code I'm:
  • Requiring the express module, and assigning it to a constant field.
  • Creating a router to manage my endpoints
  • Creating a GET endpoint for directly accessing my server which will return (for now) "Hello World" message as a text response. We will replace this static message later on with different content.
  • Configuring my router to be pre-fixed with /api/ for accessing all endpoints.




Now, let's run our program to see if it works.


Before we move forward to testing my API, I want to add one more important thing. I want to define my start script. 
I will open the package.js file and add a "start" script which is going to run my index.js file when I run $npm start.




Now let's test our API. 

For this part I'm going to use postman (I can actually use a vs code plugin, but just to keep it simple, let's stick to the basic tools).



And it works... :)

I hope you have enjoyed this post. In part 2, we will continue to building our endpoints, generate actual data that we can retrieve via our API calls, and work on our controllers with appropriate error handling and status codes. 





Comments

  1. I like your writing, try to add the code as text, it will make things easier

    ReplyDelete

Post a Comment

Popular posts from this blog

Sharing is caring - Intro to Jenkins shared libraries

Intro to Terraform and how it is related to test automation infrastructure

Test Automation, Security, and other vegetables