Simple APIs with Node.js
Hello, in this article I want to go over a super simple example of using Node to create an API. This API will have three different responses to show how easy it can be to request and return the various responses that our API will give. Let’s get started.
Install Node
If this is your first time using Node you will need to head over to https://www.nodejs.org and download a version to your system. I recommend using the LTS version as it is the more stable version.
If you already have Node installed please make sure that it is at least version 12.x.x or higher and you should be in a good spot to follow along.
If you are a version of Linux you can use
# Debian based:
sudo apt-get install node# Arch Based:
sudo pacman -S node
Our First Node API
Now that Node is installed the first step is to make sure that it was installed correctly to do that we are going to write some command in our terminal. Please open up your terminal or command prompt if you are on Windows and type the following commands:
$ npm --version
$ node --version
If you used the website to install Node then you should get the version number that matches what you installed from the site. If you used your operating system package manager such as apt or pacman then as long as the version you get back is 12.x.x or higher you are good.
We can now write our first API. This isn’t going to be super fancy or anything like that. This is just meant to show how easy it can be to get started with Node. Open up your text editor. I typically use VS Code if you have VS Code installed and you left your terminal open then follow along:
$ cd Desktop
$ mkdir node-api
$ cd node-api
$ code .
These commands above change your current directory to the Desktop, create a new directory called node-api, change into that newly created directory and then open the current directory inside of VS Code. Now that VS Code is open we can create our first file.
app.js
const http = require('http');const port = process.env.PORT || 8080;const server = http.createServer((req, res) => {
res.end('Hello from Node');
});server.listen(port);
console.log(`Server listening on port ${port}`);
We can run this file by switching back to our terminal and typing:
$ node app.js
There should be a message in the console now telling you that your server is listening on port 8080. Open a browser and type localhost:8080 and hit enter you should now see
Congratulations you just created your first API with Node. Pretty easy right? However it doesn’t really do much good when you are returning plain text. Plain text isn’t quite the go to response data for an API. Let’s change that. In the next section we are going to return JSON.
Going Over the Code
Before we move on to returning JSON I want to break down what we have so far.
const http = require('http');
This line is importing the built in http module that Node uses in the core features. Require is a global function in Node and is always available. http is a core module, this means that it’s always available to be loaded using require().
const port = process.env.PORT || 8080;
We are choosing which port the server will listen to for requests. We store it inside the port variable. process is similar to the require function in that it is globally available.
const server = http.createServer((req, res) => {
res.end('Hello from Node');
});
Here we create an HTTP server object and assign it to the variable server. http.createServer() accepts a single argument: a request listener function. The request listener function will be called every time there’s an HTTP request to our server. In other words everytime we visit localhost:8080.
server.listen(port)
Here we are taking the server object and calling the listen method passing in the port variable we created earlier so the server knows which port to listen for requests on.
console.log(`Server listening on port ${port}`);
Last but not least we send a message to the console showing that are server is running and which port the server is running on.
Returning JSON
As mentioned earlier, web apps and distributed systems commonly use JSON APIs to serve data. We can manage this with just a slight tweak to our code. modify the server object like this:
const server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ message: 'Hello from Node',
lucky-numbers: [42, 3, 27] }))
})
You don’t need to make that a second line it did that because the code window on this post is only so big.
It is best to be explicit with responses so that clients (browsers and other consumers of APIs) don’t handle the data in unexpected ways. By sending plain text without a Content-Type header, the client had no idea what kind of data to expect.
Break Down of the Code
As you can see in this example we have explicitly informed the client of the type of data that it will be receiving. In this case JSON. Let’s run the code now and see what happens. First you will need to stop the server using ctrl + c, then run the following:
node app.js
Awesome we get our data back in the form of JSON. Don’t worry if your browser doesn’t look exactly like my screenshot I am using a version of Firefox that has a pretty printer for JSON. If you are using Edge(Chromium) or Chrome you can find the an extension for it.
API Routing
In this final section we will take a look at how to make an API have different routes that will display different data depending on which route was chosen. Let’s get started.
First let’s go ahead and stop our server from running using ctrl + c. Not all client requests are the same, and in order to create a solid API you will need to be able to respond differently depending on the requested url path. As some of you may have noticed we have an argument in our server object that we aren’t doing anything with, req. Well we are going to start using that right now.
We are going to update our app so that depending on the request our API will respond with plain text like the first time, JSON like we just did or a 404 Not Found error. Handling errors is always a valid and required skill to have so we are definitely going to showcase how we do that. Let’s start
We are going to create functions that will handle our data requests. Just above where we create our server object let’s add these new functions. I am going to be using arrow functions but feel free to use whatever method of creating functions suits your fancy.
const respondText = (req, res) => {
res.setHeader('Content-Type', 'text/plain');
res.end('Hello from Node!');
}const respondJson = (req, res) => {
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ message: 'Riddle me this Batman?', luckyNumbers: [42, 3, 27]}))
}
As you can see most of this code should look familiar to you. The first function is taking setting our header to plain text and then returning our message from before. The second one is just like our JSON example from earlier. I changed the message so you could see it in action and didn’t think that it was the same thing.
Now for the final function which will return an error of 404 not found. We are going to use a different response method. The concept is similar to the other two functions but I want you to pay close attention to the method called.
const respondNotFound = (req, res) => {
res.writeHead(404, {'Content-Type': 'text/plain'});
res.end('Not Found');
}
Now that our functions are created we can now update our server object code to call the corresponding route.
const server = http.createServer(req, res) => {
if (req.url === '/') return respondText(req, res);
if (req.url === '/message') return respondJson(req, res); respondNotFound(req, res);
});
We are using if statements to determine whether a route is requested. If it is the home or index route, ‘/’, we return the plain text. If the route is ‘/message’, we return our JSON message. And if we go to any other route it will return the 404 error not found. Let’s try it out.
index route
message route
Not Found
And that is it. We now have a working API that allows us to return different kinds of data depending on the route requested. I hope you enjoyed this article.