Learn to Code an API in JavaScript

Hey there! Yeah, YOU!

I know why you’re here.You’re looking to gain a better understanding of APIs and JavaScript, and you’ve come to the right place.

I hope you enjoy the tutorial, and if you do, please leave me a comment or clap. It’s very motivating to hear any feedback or find out that the content was useful.

Anyways, hope you enjoy. Cheers

This tutorial is based off of Max Sandelin’s video series here:

  1. Learn to Code an API in JavaScript — Part 1
  2. Learn to Code an API in JavaScript — Part 2
  3. Learn to Code an API in JavaScript — Part 3

This is going to be a TON OF FUN so grab your joe and lets dive in!

Image for post

p.s. just an idea: if you get some value out of this article, and you’d like to support the author, purchase your next Amazon shipment through my affiliate link here. Cheers!

TABLE OF CONTENTS

  1. Clone the Todo list app from Github
  2. Open up the files in your Text Editor
  3. Install node.js (video)
  4. Install Express with NPM
  5. Git (video)
  6. Set up Express Script for your API (video)
  7. Serve our Todo List App (video)
  8. Create our first Post Route (video)
  9. Connect our Todo Button in the Todo List App (video)
  10. Set up MySQL Database (video)
  11. Connect API to MySQL
  12. Insert New Items into Database
  13. Update Item States in Database
  14. Delete Items from Database

FAIR WARNING… I’M STILL TROUBLESHOOTING A BUG WITH MYSQL FOR STEPS 12–14 SO THIS IS NOT A COMPLETE TUTORIAL… YET… IF YOU’RE INTERESTED IN A PUZZLE, ERROR MESSAGE HERE

Step 1: Clone the Todo list app from Github

Max’s github repo is here. Fork it to your own github repo, and then download it to your desktop.

I’m going to create a new folder in my documents directory and clone the file there on my desktop…

Opening up terminal…

cd Documents

then

mkdir todoAPI

then

cd todoAPI

make sure you have copied the github link to clone it…

Image for post

And then…

git clone https://github.com/deallen7/todo.git

And boom!

Image for post

then change directory into the new folder…

cd todo

and check out your new files inside that folder with…

ls
Image for post

Great. We’re on our way.

Image for post

Step 2: Open up the files in your Text Editor

Some steps are really small. Celebrate them all.

I like using Sublime Text 2, and I love this integration with the terminal where I can open up any directory with a simple:

sublime .

Set your computer up the same way with this tutorial.

Step 3: Install node.js

You can find it here.

We are here in Max’s video.

If you aren’t sure if you have it or not, just type this in your terminal:

node -v

You may get something like this:

Image for post

We will be using Node, NPM (node package manager), and Express (a webserver for node)

Go ahead and check your NPM version at this point, too:

NPM -v

I’m using v 5.6.0

Step 4: Install Express with NPM

Head over to expressjs.com and run through the “Getting started” guide (here).

First step for me:

npm init -y 

this will generate a package.json file for you…

Image for post

which you’ll see in your terminal (as shown above) and in your text editor:

Image for post

now we need to run the install…

npm install --save express

Output from terminal looks like this:

Image for post

Now check your text editor for a file filled with node_modules. There it is at the top.

Image for post

Step 5: Git

At this point in the tutorial, Max decides to create a feature branch called “api”. I’m going to follow his lead.

git checkout -b api
Image for post

you can view the branches with this command:

git branch
Image for post

Neat-o.

Now, we’re going to create a .gitignore file so that we don’t upload our entire node_modules file to git…

you can do it in the command line with:

touch .gitignore

Head over to https://github.com/github/gitignore and find the node.gitignore template…

(it’s right here)

Copy / paste of all that junk into your file.

SAVE!

Now we are going to commit the file…

git status
Image for post

then add all your files…

git add -A

or you can also do:

git add .

one more status…

git status
Image for post

commit…

git commit -m "initiated API work"

Ok cool…

Now I’m going to merge my feature branch into my master.

git checkout master

then

git merge api 
Image for post

then

git status

and then I’m going to push

git push

terminal tells me:

Image for post

Now I’m going to refresh my github repo and see if the changes made it up to github…

Suuuuuuucccesssss.

Back over to my feature branch to continue…

git checkout api

and check that I’m on the right branch with:

git branch
Image for post

Great.

Step 6: Set up Express Script for your API (video)

Max says “Since node is JavaScript, we’re going to need a JavaScript file”

To clean things up a bit, Max creates a src folder, and then a public folder inside the src folder.

Hierarchy looks like:

Image for post
Image for post

Now, create a new file called index.js inside the src file…

Image for post

This will be the actual API file…

Now, inside that file, we’re going to pull in express…

const express = require('express');

and then set up the api…

const api = express();
api.listen(3000, () => {
console.log('API up and running!');
});

SPECIFIC VIDEO SECTION OF THIS EXERCISE IS HERE

Now we will set up the routes…

“routes are specific paths (urls) for your domain”

“We are running locally so it is local host 3000”

api.get('/', (req, res) => {
console.log(req);
res.send('Hello, world!');
});

“when someone runs a get request for a specific path, we want to do something”

Whole file looks like:

const express = require('express');const api = express();
api.listen(3000, () => {
console.log('API up and running!');
});
api.get('/', (req, res) => {
console.log(req);
res.send('Hello, world!');
});

SAVE THE FILE.

Now, in the command line, write:

node ./src/index.js
Image for post

and then navigate to localhost:3000 !

Image for post

Allllllriiiiiighhhht.

Image for post

Thanks Matthew!

And then check out the console!

Look at all this data…

Image for post

Sweet. That’s the end of video 1.

ctrl + c to kill the API on your Mac.

Max doesn’t commit his work to github, but we should go ahead and get some git practice in, don’t you think?

git status

then

git add .

then

git commit -m "added api js file"

then

git checkout master

then

git merge api

then

git push

Cool. We done. We gone. We on to video number 2!

Step 7: Serve our Todo List App

We will use something from Express called “static”

Static is an Express method. Read about it here.

We will also be using a “middleware” function called .use

api.use((req, res, next) => {
console.log('Hello');
});

toss this into your index.js file, save, and let’s run the API again…

node ./src/index.js

Head over to http://localhost:3000/ and you’ll notice that the page never completes loading…

That’s because we need to run the “next” function.

api.use((req, res, next) => {
console.log('Hello');
next();
});

Save, and then restart the API by running:

node ./src/index.js

You’ll noticed that localhost3000 completes it’s load this time.

To learn more about middleware, head over to express.js.com and check out the guides on middleware.

Image for post

So that was just a bit of a tutorial in middleware, but we’re actually not going to write our own middleware, we’re going to use express.

So instead of this:

api.use((req, res, next) => {
console.log('Hello');
next();
});

We will use this:

api.use(express.static(__dirname + '/public'));

this is handy:

__dirname

This above will let our program access this directory even if we move the folder around our system. Cool.

Now we can also comment out this:

api.get('/', (req, res) => {
console.log(req);
res.send('Hello, world!');
});

File looks like this:

Image for post

SAVE, and let’s run our file again!

node ./src/index.js
Image for post

Sweeeeeeet.

Image for post

Now let’s test our app!

Image for post

Oooooooo yeah.

Nice. We done. Time for a git commit.

BLAST! I realized I never switched back to the api feature branch. Phoey.

Oh well.

git add .

then

git commit -m "serve todo list app"

then

git push

then done. Next!

Step 8: Create our first Post Route (video)

Back inside the index.js file…

api.post('/add', (req, res) => {
console.log('Post request received');
});

run the thing…

node ./src/index.js

And check this out. Go to http://localhost:3000/add and you’ll see….

Image for post

That’s because we wrote a POST request. Not a GET request.

Now, let’s checkout out Postman. Go download it if you don’t already have it.

In Postman, we’re going to create a new POST request for localhost:3000.

Check it out:

Image for post

Oops! That’s an error. We need to send our POST request to localhost:3000/add

Image for post

This will never complete, but check out your terminal. See what it logs?

Image for post

Post request received!!!

Now, shut down the server. Update the POST request code to:

api.post('/add', (req, res) => {
res.send('It works!');
});

Send another POST request in Postman…

Image for post

And BOOM! It works!

Step 9: Connect our Todo Button in the Todo List App (Video)

Now, let’s connect the add todo button to the API so that we can receive the data on the API end.

Open up the main.js file…

Image for post

Find the add button in the index.html file….

Image for post

There it is… id=“add” on line 24

Now let’s find the associated event listener in the main.js file…

Image for post

There it is! Starting with line 15.

Great. We know how things are working here. If the add button is clicked, do THIS THING

document.getElementById('add').addEventListener('click', function() {
var value = document.getElementById('item').value;
if (value) {
addItem(value);
}
});

THE THING? addItem(value).

addItem(value) to what? A DATABASE. That’s what. Right now the todo item is just hanging out in local storage. Now we’re going to create a method for sending the to-do item to API

First, create a function in the main.js file alllll the way at the end of the file:

function sendItemToAPI() {}

Then, find line 32 in your main.js file and add the function like so:

function addItem (value) {
addItemToDOM(value);
document.getElementById('item').value = '';
sendItemToAPI(value);
data.todo.push(value);
dataObjectUpdated();
}
Image for post

Update your sendItemToAPI function to:

function sendItemToAPI(item) {
console.log(item);
}

We included the console.log(item) line to test our function.

Run the server with:

node ./src/index.js

And then try adding a new todo item to your app at localhost with the google chrome console is open…

Image for post

COOL! All the way down there at the bottom. Success.

Now we can delete that console.log line.

Ok, full method:

function sendItemToAPI(item) {
var req = new XMLHttpRequest();
req.open('POST', '/add');
req.send(item);
req.addEventListener('load', () => {
console.log(req.responseText);
console.log('Request done!');
});
req.addEventListener('error', () => {
console.log('Shit, something bad happened.');
console.log(e);
});
}

Now, back in the index.js file… Update the api.post to:

api.post('/add', (req, res) => {
console.log(req.body);
res.send('It works!');
});

Like so:

Image for post

Now we are going to use body-parser to do some stuff. What stuff? I don’t know yet. Let’s continue with the video. Here’s the link to the body-parser github.

So kill the server.

In the command line:

npm install --save body-parser

Great.

Image for post

then…

on top of the index.js file, add:

const bodyParser = require('body-parser');

Like so:

Image for post

Ok, more typ typ typing… Add the following on line 6

api.use(bodyParser.json());

Like so:

Image for post

Now, back in the main.js file, update this line:

req.send(item);

to:

req.send(JSON.stringify({ item: item }));

SAVE YOUR WORK!!!

Restart the server…

node ./src/index.js

If you don’t like typing this you can check out video here and change this command. Me? Nah.

Ok, now refresh your OOOOOPPPPS, Max made a mistake. Rewind.

We need to update our sendItemToAPI function:

function sendItemToAPI(item) {
var req = new XMLHttpRequest();
req.open('POST', '/add');
req.setRequestHeader('Content-Type', 'application/json');
req.send(JSON.stringify({ item: item }));
req.addEventListener('load', () => {
console.log(req.responseText);
console.log('Request done!');
});
req.addEventListener('error', () => {
console.log('Shit, something bad happened.');
console.log(e);
});
}

Notice this line:

req.setRequestHeader('Content-Type', 'application/json');

That is very new.

Ok, trying again. Kill server, restart it and add a to-do item. REFRESH YOUR LOCALHOST PAGE AS WELL. Check the terminal!

Image for post

Niiiiiiice. We deserve a gif.

Image for post

Commit time.

git add .

then

git commit -m "connected todo input to api"

then

git push

cool. NEXT!

Step 10: Set up MySQL Database (video)

TIME TO CONNECT TO A DATABASE.

Install MySQL.

Here are the installation steps.

Here is where you download.

MOVING ON!

Open up a new terminal window and start mysql. You don’t want to be inside your todo app:

mysql -u root -p

You’ll need to enter your password.

Next we need a package from npm called mysql2…

You need to run this inside your todo app…

npm install --save mysql2
Image for post

Next, in the index.js file…

const mysql = require('mysql2');

First three lines look like this now:

const express = require('express');
const bodyParser = require('body-parser');
const mysql = require('mysql2');

Then we need to create a connection…

const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'todo' //dont have this yet
});

Then lets create a red flag that will pop up if there is a mistake:

try {
connection.connect();
} catch (e) {
console.log('Oops. Connection to MySQL failed.');
console.log(e);
}

Now, let’s create a new file under the src folder called data.sql

Inside that database:

CREATE DATABASE todo DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci;

Now we need a table…

Full database looks like:

CREATE DATABASE todo DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci;CREATE TABLE tasks (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
description VARCHAR(64) NOT NULL,
completed TINYINT(1) NOT NULL DEFAULT 0,
created DATETIME NOT NULL DEFAULT NOW(),
last_updated DATETIME NOT NULL DEFAULT NOW() ON UPDATE NOW()
);

Now, inside of your terminal… the one with mysql open…. copy/paste:

CREATE DATABASE todo DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci;
Image for post

Great! A warning :/

Google that sh!t. Found here that you can query warnings with:

SHOW WARNINGS;

Image for post

Phew. It’s just the ‘utf8’ being depreciated. Moving on.

Now, type in:

USE todo;

And you’ll see a message that says “Database changed”

Now, copy/paste in the create tables code…

CREATE TABLE tasks (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
description VARCHAR(64) NOT NULL,
completed TINYINT(1) NOT NULL DEFAULT 0,
created DATETIME NOT NULL DEFAULT NOW(),
last_updated DATETIME NOT NULL DEFAULT NOW() ON UPDATE NOW()
);

You’ll see:

Image for post

Then… SHOW TABLES;

Image for post

Greeeat. Next try DESCRIBE tasks;

Image for post

Ok. We’re G2G.

Test your api to make sure everything is still working…

Back in the terminal window that is inside the todo directory…

node ./src/index.js

Add a new todo in your browser, and…

Image for post

Cool. That is good stuff.

Step 11: Connect API to MySQL (video)

In the index.js file…

Update the api.post to:

api.post('/add', (req, res) => {
console.log(req.body);

connection.query('INSERT INTO tasks (description) VALUES (?)', [req.body.item], (error, results) => {
if (error) return res.json({ error: error });
connection.query('SELECT LAST_INSERT_ID() FROM tasks', (error, results) => {
if (error) return res.json({ error: error });
console.log(results);
});
});
});

Step 12: Insert New Items into Database

Step 13: Update Item States in Database

Step 14: Delete Items from Database

Hey! I’m glad you’ve made it to the end. I’m experiencing some issues with MySQL that I’m still troubleshooting…

If you can help, drop me a comment :)

Otherwise, you’ll find me on stackoverflow…

ERROR MESSAGE:

Image for post

Written by

Documentation and tutorials on Python, Programming, and Data Analysis. FPL Addict. Occasionally writing about biohacking, PMing, and food.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store