API Tutorial in JavaScript – Part 1

API Tutorial in JavaScript

This is Easy Software Developer and a big part of making things easy for developers is selecting the right tools for the job and when it comes to quickly and easily creating APIs these are my tools of choice:

NodeJS, ExpressJS and Postman to test our API.

Prerequisites

Before we start, here are a few things that I won’t cover in this tutorial but you should already have installed or be familiar with:

  • Visual Studio Code or another text editor.
  • Basic command line knowledge
  • Web development knowledge

Luckily I have written articles that cover all of those topics here they are:

Great, now that we got that out of the way, let’s dive in and start with the most important bit, NodeJS

NodeJS

There’s a really cool definition of what NodeJS is and I’m sure you can read that anywhere on the web, but this is Easy Software Developer and I’ll simplify it.

NodeJS allows you to run JavaScript on the server(backend) instead of on the browser(frontend).

To install NodeJS, just visit https://nodejs.org/en/download/ and pick the right version for your computer.

NodeJS download page

If you run into any issues during the installation, try to Google them because it’s very likely that someone else has gone through it before.

If everything goes well you should be able to write node -v on your console and get the node version you installed.


We could actually stop here, not install ExpressJS and build out API, but I think that ExpressJS makes things much easier for us. Since it’s a framework that works on top of NodeJS, it abstracts a lot of things for us, so let’s get it installed.

ExpressJS

When you installed node, it actually gave you access to something called NPM as well. If you have worked with modern frontend libraries like ReactJS or Vue then you might be familiar with NPM, but if you aren’t then read on 😎.

NPM is basically a collection of packages that you can easily install in your application. For example, if you need some advanced mathematical functions that you don’t want to spend time implementing, you can easily find a package that has them and use it in your program.

ExpressJS is a package just like that. Let’s start by creating a folder called “myapi”. Now open that folder with your text editor.

You want to create a file called “app” and make sure that it’s saved as a JavaScript type like shown below.

Creating the app file

Remember that you’re doing all this through the text editor.

This file will hold all of our api code.

Before we can use ExpressJS, we need to install it. You can easily do this by navigating to the api directory through the command line or opening a new terminal if you are using Visual Studio Code(which I recommend).

Visual Studio Code terminal

Now we can run: npm install express –save

Just like that we installed ExpressJS 🎉.

Postman

Before we start writing code for our API, we need to have a proper way to test it, and currently one of the best applications to do it is Postman.

You can download it here.

Postman download page

Postman will allow us to test every facet of our API. This is by far my favorite tool for testing APIs!

By the way, you can skip the sign up step and just use the app without an account.


The Code

Alright, now we are all set to start writing some code.

We’ll create an endpoint called greeting . This endpoint will accept two types of requests, a GET(fetching data from existing records) request and a POST(when sending data to the app to create a new record) request.

const express = require('express')
const app = express() // Creating an expressjs app
const port = 3000 // Setting the port where our API will be listening to
// Defining the first response for our greeting endpoint
app.get('/greeting', (req, res) => res.send('Welcome to the Greetings API'))

// Making sure that the server is listening to requests
app.listen(port, () => console.log(`Greetings API listening at http://localhost:${port}`))

That’s the basic example of a GET request. We’ll make some improvements to it on our next part when we implement the database.

Now we’ll build our basic POST request handler and for this we’ll need to use Postman to test.

const express = require("express");
// We need this package in order to be able to parse the data sent to the API
const bodyParser = require("body-parser");
const app = express();
const port = 3000;
// Pretty straightforward. We are telling our app to use this package automatically.
app.use(bodyParser.json()); // support json encoded bodies

app.get("/greeting", (req, res) => res.send("Welcome to the Greetings API"));

app.post("/greeting", function (req, res) {
  // We send back a greeting with the person's name.
  // Can you tell me on Instagram what can go wrong on the line below?
  res.send(`Welcome to the Greetings API, ${req.body.name}.`);
});

app.listen(port, () =>
  console.log(`Greetings API listening at http://localhost:${port}`)
);

Wow, I’m actually amazed at how basic you can make an API. We’ll definitely make this even cooler on the next article, but first let’s test this.

Open up Postman and create a request like this:

Postman test configuration

Pay special attention to the highlighted areas. You need to make sure that you select POST as a request type and add a Body of type raw and JSON.

That JSON should look like this:

{
	"name": "Easy Software Developer"
}

Once you set all of those things up, you can press Send and the request will be made. Postman will display the results of the request below the and it should read “Welcome to the Greetings API Easy Software Developer“.

If you see that message, you can celebrate! You created a basic API.

I know that this is really basic stuff, but don’t worry, on the next article we’ll dive deeper and make things more advanced by adding a database and creating other type of request handlers.

I hope that this article helped you understand how APIs work. If it didn’t, hit me up on Instagram @easysoftwaredeveloper and ask me anything.

Thanks for reading, see you on the next article!

Leave a Reply

Your email address will not be published. Required fields are marked *