Learn nodejs, Serving JSON data

We can also use the HTTP module to create an HTTP API, or a server whose primary purpose is to serve JSON data. APIs are used to serve data to client applications. These applications typically include mobile apps, and single page websites, but, any client who can make an HTTP request can communicate with an API.

So,let’s go take a look at our Exercise Files, under the start folder, you will notice that there is an empty JavaScript file called api.js. And then, we have a data folder, and inside the data folder we have an inventory.json file.

So, I’m going to go ahead and take a look at this file. So, this is just a JSON file that contains an array of inventory items. Each of these objects represent one of the inventory items. And, a couple of these items are in stock, so if we check the availability node, we can see that we have about three items in stock, here, and one of our items, our K-Eco 225s, are on backorder. So, this is the data that we are going to serve through our API.

Let’s go back to our Exercise Files, and open up the api.js file. And, the first thing that we’re going to need to include is the HTTP module, so we can require that. And now, the next thing we need to include is that inventory data, that JSON file, so, I’m going to create a variable for data. And, we can also require JSON files with the common JS module pattern, so, I can require simply a link to data inventory, and now, that data variable will represent JSON data that is found in the inventory file.

So now, we need to create our server. And, of course, we need to add the callback function, that will fire for every incoming request. And pass the request and response objects as arguments to this function. And, I’m also going to chain on our listen function to tell the server to listen to port 3000. And, we’ll go ahead and log listening on port 3000. There we go.

So, when creating a JSON server, all we need to do is identify the content that we are responding with as JSON, so, we’re going to go ahead and write our Head with a 200 success, and we will add headers for the content type, and this content is text/json. Great. And now, all we need to do is send our data back. So, I’m going to go ahead and end this response, and I can use the JSON.stringify method of JavaScript, to go ahead and stringify and return my data as a JSON string.

So now, when we hit this server, we will reply with the JSON inventory data. I’m going to go ahead and save this, and head out to my Terminal. And now we can run this by running node api. And we see we have a server listening on port 3000. So, I’m going to head over to the Browser, and I can go ahead and open up a New Tab, and hit localhost 3000. And here, we can see that this web server is responding with our JSON array. Any app that can an HTTP request will receive this JSON data.

So, it’s a great way to pass data to and from the client. Let’s go ahead and add another iteration on this project. What we’re going to also do is provide a couple of routes. So, what we’re going to allow our users to see is, all of the inventory, or just those inventory items that are in stock, or, just the list of inventory items that are on backorder. So, the first thing that we’re going to do is, we’re going to create a couple of functions. And, I will add these functions to the bottom, that will help us search our data.

So, I’m going to go ahead and add a function for listInStock. So, we’re going to use this JavaScript function to list the InStock data, and I’m going to go ahead and grab another function, here, for listOnBackorder. Now, we’re going to send the response object to these functions. So, I’m going to make sure that both of these functions take in the response object. And what I want to do is, I want to list all of the items that are In Stock in my data. So, I’m going to go ahead and create a variable for inStock, and I’m going to set this = data.filter.

So, the data is an array, it has a filter function. We use the filter function to filter out those data objects in our array for specific details. So, this function will take in a callback function, and this callback function will be invoked once for every item in the data, so, once for every one of our inventory items. And now, this function is what we would refer to as a Predicate. It should only return a True or a False. If this function returns True, then we are going to add this data item to a new array.

If it returns False, then we will skip adding this inventory to our new array. So, what we want to do is return a True or False, as to whether this inventory item should be added to the new array. So, what we’re going to do, is, the inventory item itself, is going to be passed as an argument to the callback function inside of the filter function. What we want to do now, is, return either True or False. And, we’re going to return whether or not the items available key is equal to In stock.

So, for every item that has the availability marked In stock, those items will be added to this new array. If the item is on backorder, it will be filtered out of this new array. Now, what we’re going to do is, is we’re going to do the exact same thing in the listOnBackOrder, but, when we list the BackOrder items, we are going to actually be looking for OnBackOrder, instead of InStock. So, I’m going to add On back order here, and, I’ll actually change this variable two to be onOrder.

So, listing InStock items will filter my data to display just those items In stock, and listing OnBackOrder items will filter my data to just list those items On Order. So, now that we have the appropriate data filters, let’s just go ahead and use our response object, and we will end it by stringifying our filtered data. So, we’ll stringify the inStock items inside of this function, and, down here, in our OnBackOrder, we will go ahead and respond by stringifying our onOrder items.

Great. So, we have functions that will respond with filtered data. What we need to do is go ahead and add these functions to our web server. So, I’m going to scroll up here, and here, we are responding on line nine, with the full array of inventory data. What I want to do is just throw and if else block in here. So, if the requested url is equal to the homepage, that’s when we want to respond with all of the data.

So, if you’re requesting the home page, we will respond with all of the data. We will respond with a 200 successful response, Content-Type text/json, and we will stringify all the data. Otherwise, else if the requested url is equal to /InStock, then we are going to respond with the InStock data. And we can use our listInStock function, and send our response to that function. Otherwise, if you are looking for, so, the requested url is equal to onBackOrder, or onorder, then we will go ahead and listOnBackOrder, and send our response object.

Finally, if you aren’t looking for any of these routes, we’re going to assume that we have a 404 request, so I’m going to respond with a 404 status. And, we’ll go ahead and add our Headers. This time we’re going to respond with text/plain, and now we will also go ahead and end our response with Whoops… File not, or Data not found. There we go.

Great, so now we have finished our JSON server. Let’s go ahead and save it, and navigate to our Terminal. And, our old server is still running, so we need to go ahead and stop that with a Control C. I can go ahead and node api again, so that we can run our new file with the latest changes. And let’s go ahead and go out to the Browser. Now, if we go to localhost 3000, we get all of the items, but if we go to localhost 3000/instock, we get a filtered list of those items that are only in stock.

If we go to localhost 3000/onorder, we get a list of those items that are on backorder. So, client applications, client web applications, they can all communicate with this API and find those items that are in stock or on backorder, or just receive the whole list. Building JSON APIs is a powerful feature of the Node.js Create Server. So, these are the techniques that we will need to construct APIs, or middle tier web applications, that just serve JSON data to clients.

Leave a Reply

Notify of