To watch the youtube video where I go through all the steps with you and explain how the code works, click here. (Recommended.)
APIs - Introduction
So we want to make an API. If you've seen the previous articles (in a series on APIs I've been doing), then you know what an API is, and you've planned out what our API should do, and were even very specific by making a Swagger document.
Now we're going to make an actual API using NodeJS, and we'll eventually host it on Heroku.
First, make sure that you have NodeJS installed. As usual, the commands shown will be used in a terminal on Ubuntu 16.04. They may work on other versions of linux, but if not, just find out how to use it on your preferred OS.
We'll need to install some packages using npm, but we'll do that later.
Start With a Node Project
We're going to start by creating a boilerplate node project. In the command line in your project folder:
For the name, enter "srcmakeapi", for the version enter "1.0.0", for the description you can enter "srcmake api tutorial", and for the entry point enter "index.js". For everything else just press enter.
The previous command has generated a package.json file in our project folder. The package.json file will hold the descriptive information for our project, as well as the node libraries that we're using.
Let's actually install the libraries that we need. The following commands will install the libraries, and include them in our package.json file.
Express is a framework for handing the routing of our server, and body-parser will help get content out of the requests made to our server. Nodemon will allow us to make changes to our code, without having to restart the server every time.
Setting Up The Server
The first thing we need to do is make our project act like a web server, meaning it needs to accept requests from URLs.
We defined our entry point to the application to be index.js, so create a filed named "index.js" and add the following code to it:
The first line defines our app by requiring something from a file named "server". The rest of the code tells the server to listen on port 3000.
Let's create this server functionality by creating a file named "server.js". Add the following code to it:
Here, we declare variables for express, body-parser, and our project directory. We then use express to create our server by invoking it into a variable named app. We let our app use some stuff, for ease of parsing.
Next, we declare a variable named 'routes' that stores what's exported from a file named v1_routes (which we haven't created yet). Our app is then told to pass all requests that begin with /v1 to the routes variable (which is our v1_routes file). Our final line exports this app as a module (so that it can be used in another file (which is what we were using in index.js)).
With that, our server is setup, but nothing is actually happening yet. We need to declare the specific routes for our API. Specifically, we need routes for /add, /subtract, and /check for our Fruits API functionality. We're going to handle that in the next section.
(This might seem convoluted, but when you have a real API with a lot of functions, it's better to understand how to spread everything out so there aren't gigantic files that no one is able to read.)
Set Up The Path Routing
Okay so our server is set up, but we need to set up some routes to handle each of the paths that we in our API. We're going to do separate the routing from the functionality.
First, create a folder named "routes", and then create a folder named "controllers" in the project's root directory. The routes folder will hold files that handle the routing (meaning the mapping of our API route (the URL)) to it's appropriate function. The controllers folder will hold our controller files, which will define the functionality of each of our endpoints in the API.
For example, srcmake.com/v1/add is a valid API path. The server will route the request to the v1_routes file, because the request begins with v1. Our v1_routes file will map the add functionality to an add controller in the controllers folder. And that add controller will be a function that adds fruit to our database.
Inside of routes, create a file named "v1_routes.js" and add the following code to it.
The code is very basic. As mentioned, it routes the endpoints ("/fruits/add", as an example) to a controller that will handle the functionality. Notice that we define the HTTP method (post and get) in the routing.
As you can see, we need a controller named fruits in our controllers folder, so create "fruits.js" inside the controllers folder. Add the following code to it:
Our fruits controller exports three functions that do nothing right now. However, these functions are handled correctly by our routing and will eventually be filled out with code that handles our desired API functionality.
We can test our app right now. We won't do a good test (that comes later), but we will test to make sure that our code is working. In the terminal, type
Nodemon will start our server.
Test our server by going to localhost:3000/v1/fruits/check in your web browser. Your terminal should show you an output to the console. (You can try our /add and /subtract methods, but those are POST methods! The browser only initiates GET methods.)
Create Our Desired Functionality For Each Endpoint
Okay so our API is routed beautifully, but it doesn't actually do anything useful yet. We need to beef up of fruits functions by making them send status codes and responses.
It's actually really easy to parse the url parameters, send status codes, and send responses using Node. It's actually INCREDIBLY easy, which is why NodeJS and Express are so popular.
Update our fruits.js file to the following:
The only change is to our "check" function. We first parse the parameters in the API query (which we output to the terminal.) We send a 200 OK status code, and we send a response string back to the user.
If you have it turned off, then use nodemon to turn your server back on.
Test our check function, this time giving it a parameter. In your browser, go to http://localhost:3000/v1/fruits/check?fruitname=apple . The terminal should output apple, and the browser should display our string.
That's a demo of how input and responses work, but since we're coding this API specifically for our fruit functionality, let's add exactly what we expect based on the functionality each API function should have.
Update fruits.js one more time, with this code:
For the /add and /subtract functions, we simply return a 200 OK response along with Success. For the check function, we return the fruitname and quantity as json depending on the fruit the user asked for in the parameter.
This code is very incomplete and doesn't handle databases, nor does it handle errors (such as the user giving wrong data), but that can be completed on your own or with some simple coding. I don't want to make this tutorial too long or complex, since it's aimed at beginners.
You can download the project, as it currently stands, here, from github.
Test The API Using Postman
Okay, so our code is complete. Our Node project is 100% done. However, we can't actually test the POST commands in our web browser, so how do we know if they work? We actually can test all HTTP methods in the web browser using an extension named Postman. Find it on your browser's web store and install it.
(Make sure the server is running. If not, use nodemon.)
First press the Request button and fill out the form. Add a request name, and create a collection named srcmake_API. Press the checkbox, and click Save.
Next, select POST from the dropdown menu, and enter the URL ( localhost:3000/v1/fruits/add ) and press send. You should see some json returned with "Success", as we'd expect with the way our API is currently defined.
And that's it. Play around with testing as many endpoints as you need.
Host the Project In The Cloud (Heroku)
Okay, so we have our API set up. It's a good idea to host our API on a cloud server. Fortunately, Heroku is an awesome cloud service system. Their documentation is great, and it's free! So that's what we're going to use. Feel free to view Heroku's Getting Started tutorial for NodeJS, but I'll be going through the commands so you should be able to do this without the article.
First, we're going to install Heroku (if you don't already have it installed). Run the following for commands in your Ubuntu terminal.
You also need git, if you don't have it.
Next, we're going to log in to Heroku in our terminal. (If you don't have an account, go to their website and make one.)
Next, we're going to use the the command line to prepare our heroku app. (Basically, it creates an app heroku's servers, and we need to upload our Node code to the servers.) In the command line:
There's one thing that we have to do to make our existing code work for Heroku. We need to let Heroku know what we want to do to start our code. Heroku does this through what's called a Procfile. Create a file named Procfile with the following command (Make sure you're in the root directory of our project folder.):
Inside of the Procfile, add the following line of code:
Our code is complete, so now we're going to push our code to Heroku's servers. This is done by using git to push the code to Heroku's code repository for this app. In the terminal in our project's root directory:
And that's it. Our API is officially hosted on Heroku. Use
to open our project in the web browser. Make note of the Heroku URL for our API. It should say "Cannot GET /" in the web browser, and that's understandable because our Node Project do anything for the / route. (We're also not a website...just an API.)
Test our API by going to the /check path and finding our how many Apples we have. For my particular Heroku Project, the URL is:
Change the base URL to reflect your own heroku url.
However, there's a lot that we didn't do. We didn't implement any database, and we didn't handle specific errors in our code. We also didn't handle wrong input data from the user, or returning different status codes. All of that can be easily added to this project, but would make this tutorial too long. Perhaps in another tutorial we can go over them, if there's enough interest.
Use this base project as a boilerplate for any APIs that you build in the future. Once again, the github link to the code is here. Spin this project off for whatever API you need to make. Take a look at the Java API tutorial, next. If not, then look at the Postman tutorial for a more in-depth look at postman.
Here's the video where I go through all of the above commands:
Like this content and want more? Feel free to look around and find another blog post that interests you. You can also contact me through one of the various social media channels.
Hi, I'm srcmake. I play video games and develop software.
Pro-tip: Click the "DIRECTORY" button in the menu to find a list of blog posts.
License: All code and instructions are provided under the MIT License.