Writing Restful Api in Node.js

Today we will examine how to write a Restful service in Node.Js. If we want to refer to the Restful service, even though it is short, the request transactions are provided by HTTP Methods (POST, PUT, DELETE, GET).

In this application, we will use Express.js, one of the most popular frameworks in Node.Js. Express.js creates a structure that simplifies the work we do with HTTP, and allows pre-defined definitions to be executed in each request before and after post operations or authentication and login processes.

Express.js can be downloaded using NPM as follows.

We also need the body-parser to read the JSON data from the JSON requesting server. NPM can be downloaded with the following command.

Express and bodyParser objects are defined below. As the json data, the cities object is assigned the city names and the countries to which they belong.

Now it’s time to start the server on port 1905 and run the body-parser on express.js. The following code snippet is written for this.

The following command is written to the command line. And the server starts.

As shown above, the server has started. And the corresponding log console was written. At this point, we cannot make a transaction through the browser. We didn’t create any endpoints. As shown below, the GET process creates an API that can list all cities.

When we type http://localhost:1905/api/cities from the browser, we take the following screenshot.

Now it’s time for the API to add a new city. POST will be used for this operation, and the city will be added to the existing list. If the city to be added is in the list, the error message “This city is already registered yok will not be sent and the new city will be added to the cities object. The corresponding code is below.

I used Fiddler to test the post. In the screenshot below, a json data was sent to the address http: //localhost:1905/api/cities via the POST API with the city name: Tokyo and Country: Japan.

Fiddler: Don’t forget to write “Content-Type: application / json’ to Header.

http://localhost:1905/api/cities When the URL is entered, the following screenshot is taken as a result of GET operation. As you can see, the newly added city of Tokyo and its country Japan are included in the listed cities object.

The PUT method can be used as follows. Again, results can be tested by Fiddler.

if you have question do not forget to write from the chat button next to it or from the comment

You may also like...

1 Response

  1. September 8, 2019

    […] See express doc for more. […]

Leave a Reply

Your email address will not be published. Required fields are marked *