DEV Community

Cover image for Getting started with Api development on Nodejs
Rubin
Rubin

Posted on

Getting started with Api development on Nodejs

Before we get our hands dirty and get a move on , I assume you have a sound knowledge of js .I am also assuming that you have nodejs installed on your machine.
There are plenty of web frameworks for nodejs . To point out a few popular ones, I might say express , koa and hapi. We will be going with express as it is the most used web framework for nodejs with tons of modules that are configured to work with it. Also the syntax and the learning curve is pretty easy to catch up and if you are to get stuck in a problem, there are pretty much answer to every query in stackoverflow.
To get started, lets create a directory and head over to it.After you are in the project directory, open up terminal/console and run npm init to start a nodejs project. Fill in the details as you like.After you are done , type in

npm i — save express body-parser morgan nodemon
Enter fullscreen mode Exit fullscreen mode

Hit enter and that should install and update the dependencies in package.json file.

Nodemon will monitor for any changes in your node.js application and automatically restart the server — perfect for development so you dont have to manually restart the server for viewing the changes.

Morgan is a HTTP request logger middleware for node.js .

Body-parser is Node.js body parsing middleware. It parses incoming request bodies in a middleware before your handlers, available under the req.body property.

After all the modules have been installed , create a file app.js in the root folder and open it in your favorite editor. I use visual studio code but you could go with any any text editor of your perference.
Basic Setup
Open app.js in the editor and require express module with

var express=require('express')
Now create an express instance with
var app= express()
Enter fullscreen mode Exit fullscreen mode

Routes

Now lets define some routes . A route method is derived from one of the HTTP methods, and is attached to an instance of the express class.
The following code is an example of routes that are defined for the GET and the POST methods to the root of the app.


// GET method route

app.get('/', function (req, res) {
  res.send('GET request to the homepage')
})

// POST method route

app.post('/', function (req, res) {
  res.send('POST request to the homepage')
})
Enter fullscreen mode Exit fullscreen mode

Express supports methods that correspond to all HTTP request methods: get, post, and so on. For a full list, see app.METHOD.
Here are some examples of route paths based on strings.
This route path will match requests to the root route, /. So if you visit the app in localhost:/ , you will get root printed on your window

app.get('/', function (req, res) {
  res.send('root')
})
Enter fullscreen mode Exit fullscreen mode

This route path will match requests to /about.So if you visit the app in localhost:/ , you will get about printed on your window

app.get('/about', function (req, res) {
  res.send('about')
})
Enter fullscreen mode Exit fullscreen mode

You can also use regular expressions in routes to make your routes more dynamic.

Route parameters

To define routes with route parameters, simply specify the route parameters in the path of the route as shown below.This will simply output all parameters i.e userId and bookId as an object.You can also access a single param by using
req.params.paramname

app.get('/users/:userId/books/:bookId', function (req, res) {
  res.send(req.params)
})

Enter fullscreen mode Exit fullscreen mode

Summing all of the above
The following code is an example of a very basic route.

var express = require('express')
var app = express()

// respond with "hello world" when a GET request is made to the homepage

app.get('/', function (req, res) {
  res.send('hello world')
})

app.get('/about', function (req, res) {
  res.send('about')
})

app.get('/:userId', function (req, res) {
  res.send(req.params.userId)
})

app.post('/post', function (req, res) {
  res.send('this is a post request')
})

// tell express to run on port 8000

app.listen(8000)
Enter fullscreen mode Exit fullscreen mode

Thats all for this part .

Latest comments (11)

Collapse
 
okbrown profile image
Orlando Brown

Considering all the questions being asked, and the things you plan to include, how about adding an upcoming schedule or list of all the topics you will cover over the course of time you deliver them. That way readers are informed ahead of time on how to follow and digest your content.

There are loads of tutorials of this kind, consider what is it that you bring that will be different from the rest.

Collapse
 
rubiin profile image
Rubin

sure thing. will be including that soon

Collapse
 
xgenvn profile image
Brian Ng

For me recently moleculer framework brings too much joy for API development with microservice approach.

Collapse
 
rubiin profile image
Rubin

For beginners who are migrating from frontend to backend or from other language like python, expressjs seems to be easiest for them in terms learning curve and complexity.

Collapse
 
xgenvn profile image
Brian Ng • Edited

I see moleculer is very lightweight and it brings the single-component approach for writing services, which is even easier for someone working on frontend before, with plain expressjs where we have to put many things into it:

  • Request validation
  • Documentation
  • Events
  • Logger
  • Database context
  • Security ...

But yes I agree expressjs is a good place to start.

Collapse
 
mfazz profile image
Matt

Will you be covering validation of the API requests? E.g. validating fields in the request using something like Joi?

Collapse
 
rubiin profile image
Rubin

Yeah sure. I have planned this on later in the series

Collapse
 
kamalhm profile image
Kamal

Why do you require morgan but never used it?

Collapse
 
rubiin profile image
Rubin

I will be covering that in the next post where I will be teaching on the usage of middlewares

Some comments may only be visible to logged-in visitors. Sign in to view all comments.