First API With Node.JS and Express
Here we see those steps
- Create a Project
- Install Dependencies
- Create a Server
- Create Get Endpoint
- Create Post Endpoint
Create a Project
To create a Node.JS project you need to install node/npm (or yarn), on you machine.
Please download here https://hilt.onl/nodejs .
With all set up create a folder with your project name, e.g. Test, here we will use npm as a package manager. Use the terminal of you preference to setup the project, here I’ll use Linux
~/Projects/Test$
Inside the folder type npm init, this create a default package.json with your project properties, the command will ask you some arguments
package name: (test)
version: (1.0.0)
description: This is my description
entry point: (index.js)
test command:
git repository:
keywords:
author: Me
license: (ISC)
When you finish, it’s will write a new package.json which contains the specified arguments, as follow
About to write to /home/iMaUser/Projects/Test/package.json:{
"name": "test",
"version": "1.0.0",
"description": "This is my description",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Me",
"license": "ISC"
}
Is this OK? (yes)
Confirm, and see the package.json inside the project folder. A package.json is where you describe your project to npm, how to start, your project scripts, dependencies and arguments. And also with this you can use the follow command
npm install
to install all dependencies previously saved.
Let’s create a empty file called index.js, where the npm starts the project, in next steps we will create some interesting things to interact.
Install Dependencies
We need to tell which dependencies our project uses, first we will install a dependence called Express, globally, so we can use some command lines tools in the project. Please run it with admin rights, cause this will install some global commands.
npm install -g express-generator
And now we need to tell npm that we also use the express inside the project as follow
npm install express --save
After this the follow will be add on package.json
"dependencies": {
"express": "^4.17.1"
}
Create a Server
Let’s code, open the index.js and use the code
//Tell that we REQUIRE use the express module
const express = require("express");
//Start express
const app = express();
//Listen to port 3000
app.listen(3000, () => {
console.log("It's Works. Running on port 3000");
});
So starts the application using the command
node index.js
And it’s will shows
It's Works. Running on port 3000
When we access it through this address http://localhost:3000, express says
Cannot GET /
Because we don’t have any endpoint point to “/”.
Create Get Endpoint
We have a server, but the server does nothing without some endpoints, now we can create a GET request, as follow
//GET endpoint on echo path
//Request, response
app.get("/echo", (_req, res) =>{
res.send("echo, echo, echo ...")
});
And start server again
node index.js
Go to follow address http://localhost:3000/echo, and we can see the message we returned to this path
echo, echo, echo ...
If you change the
res.send("echo, echo, echo ...")
You can customize the output.
We have a GET request, but I want to to send and read a parameter from URL. How can I do it?
Change the code
//GET endpoint on echo path
//Request, response
app.get("/echo", (req, res) =>{
//Query is a parameter from the url
let name = req.query.name
//Don't has a name?
if(!name){
res.send("echo, echo, echo ...");
//has a name
}else{
res.send("Echo? Hello " + name + "!");
}
});
Start the server
node index.js
When we access http://localhost:3000/echo, we have the same result, but if we put the parameter http://localhost:3000/echo?name=Hilton, we see the new send works.
Echo? Hello Hilton!
Create Post Endpoint
To create a POST, we need a body parser, add line in bold
//Start express
const app = express();
//Parse body as it is, you can use .json .text, and others
app.use(express.json())
//Listen to port 3000
It’s says all my request will use json, so it’s parse the data send to json format, you also can specifies by resource like this
app.post("/echo", express.json(), (req, res)
Also you can specifies your own format.
Change the code adding this
app.post("/echo", (req, res) => {
//Sends to console the received body
console.log(req.body);
//Send a OK status
res.sendStatus(200)});
Start the server
node index.js
In this example we will send on JSON format using cURL
curl -H 'Content-Type:application/json' -d '{"name":"My body"}' http://localhost:3000/echo
The output on server will be the follow
~/Projects/Test$ node index.js
It's Works. Running on port 3000
{ name: 'My body' }
And we finish a simple API server, change the code and please, send me feedback!
See you in the next post!