Node.js tutorial: RESTful API on MacOs
Today we are going to teach you how to create a WebService based on the REST architecture model.
SOAP vs REST
In this website you can see the diference between this two API Styles:
REST — Representational State Transfer is an architectural model that uses the HTTP protocol for communication. There are several representations for presenting a resource, JSON is the most used.
For this article we are going to create the following four methods:
- listarUsers (GET) — list of all users
- addUser (PUT) — add user
- deleteUser (DELETE) — delete user
- : id (POST) — Details of a user
First you have to create a directory (servernode), after that we are going to create the package.json with the code:
npm init
After this step is complete we are going to install the module Express.js with the following command:
npm install express -S
usersList Method
If the module was successfully installed, let’s move on to create the usersList method. For that we will create the app.js file with the following code:
Now we save the file and execute the following code:
node app.js
On your browser put the following url:
Should look like this:
addUser Method
To add a new user we have to add the following code (below the function to list the users):
deleteUser Method
To delete a user, we have to add the following code (below the function to add a user):
Id Method
To show the details of a user, we have to add the following code (below the function to delete a user):
The complete code should look like this: