A Step-By-Step Guide to Create your First API with Node and Express
Tags: javascript, beginners, tutorial, webdev
Published: 2020-09-26 14:26:45

Nowadays, APIs are everywhere. If you are a web developer, you probably heard about it at least one time in your life. At the end of this guide, you will have your first API with Node.Js and Express.Js.

When I started web-programming, I was coding my back-end code at the same place than the front-end one. A few months after, I discovered in my first internship how to create APIs, and it changed my way of programming.

In this step-by-step guide, we will create your first API together! I hope you like books because it's going to be around that topic. Don't worry if it's not the case! You can replace the books by chocolates, wines, anything you want!

## Pre-requirements

To create your first API, we will use Node.Js. You need to have good knowledge in JavaScript and basic one with Node.Js and the package manager NPM.

> **Note:** I highly recommend you to upgrade your Node.Js version to the last one before starting this tutorial. It will be useful to code in a modern way (ES6) and avoid potential issues in your code.

I invite you to download the software **Postman**. We are going to use it later in the tutorial.

## Tasklist for the books API

I thought it could be a good idea to create a short TODO list. Thanks to it, you will have a better idea of the main steps. It will also be useful if you want to train yourself after reading this post.

**TODO:**

1. Setup the project
2. Initialize your API
3. Create your first route
4. Create a route to get all books
5. Create a route to add a book
6. Create a route to delete a book
7. Create a route to update a book

## 1. Setup the project

Now that the TODO list is defined, we can set up the project. To do it, you should open your terminal in the folder of your choice and follow the steps below.

```shell
# Create your project repository
$ mkdir first-api-with-node-and-express

# Move into your project folder
$ cd first-api-with-node-and-express

# Initialize your Node.Js project with default parameters
$ npm init -y

# Default parameters of `npm init -y` indicate `index.js` as an entry point of the application.
# So we need to create it.
$ touch index.js
```

Once your project is set up with Node.Js, we need to install Express.js.

Express.Js is the dependency we will use to create the API. It's the most famous framework to do it in JavaScript.

```shell
# Install Express.js
$ npm install express

```

Now, if you open your `package.json` file, you will see the following lines.

```json
{
  "name": "first-api-with-node-and-express",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1"
  }
}
```

**Your project is almost ready!**

Add these lines to your `package.json` to use latest JavaScript features. You will avoid potential issues in your code.

```json
{
  /* Don't touch to the lines before */
  "dependencies": {
    "express": "^4.17.1"
  },
  /* Add the line below */
  "type": "module"
}
```

## 2. Initialize your API

Now your environment is set up, you can open the `index.js` file and start writing the code below.

```javascript
// Import Express.js
import express from "express";

// This variable defines the port of your computer where the API will be available
const PORT = 3000;

// This variable instantiate the Express.js library
const app = express();

// The code below starts the API with these parameters:
// 1 - The PORT where your API will be available
// 2 - The callback function (function to call) when your API is ready
app.listen(PORT, () =>
  console.log(`The Books API is running on: http://localhost:${PORT}.`)
);
```

Now you can run your code by typing `node index.js` in your terminal.
When the following output appears, your API is ready!

**Output:**

```shell
$ node index.js
The Books API is running on: http://localhost:3000.
```

## 3. Create your first route

APIs are working with routes. If you tried to open **http://localhost:3000**, you notice that an error appear.

```html
Cannot GET /
```

It happens because we didn't create any route at the moment.
Our API deserves its welcome route! So, we will create a **GET** route to display a welcome message.

```javascript
// The code below creates a GET route with these parameters:
// 1 - The route where the code will be executed
// 2 - The function containing the code to execute
app.get("/", (request, response) => {
  // The string we want to display on http://localhost:3000
  response.send("Welcome on the books API! Take a breath and start using it!");
});
```

Don't forget to restart your script.

**Output:**

```html
Welcome on the books API! Take a breath and start using it!
```

## 4. Create a route to get all books

Now that you created your first route, we will do the same, but this time the route will return a list of books.

**A few hints:**

- Route name: **"/books"**
- Variable: **string** list
- Return: **JSON** (JSON is the answer format used by almost every APIs)
- API Method: **GET** (because we want to GET all books)

Did you get it? Let's copy-paste the code you created in the **step 3**.

We will adjust it by doing that:

```javascript
// Static variable containing your books
let bookList = [
  "Make Time: How to Focus on what Matters Every Day",
  "The Power Of Habit",
];

// Replace the route name
app.get("/books", (request, response) => {
  // The function will return your bookList in a JSON
  // Sample: { allBooks: ["Make Time: How to Focus on what Matters Every Day", "The Power Of Habit"]}
  return response.json({ allBooks: bookList });
});
```

You can connect to **https://localhost:3000/books** to get the result!

**Output:**

```html
{"allBooks":["Make Time: How to Focus on what Matters Every Day","The Power Of
Habit"]}
```

## 5. Create a route to add a book

We have a route to get all books, but how can we do if we want to add one book to it?
In the API world, when we want to add date, we are using the **POST** method.

**What we want to do here is the following:**

- Send a book name to the API
- Treat the new book
- Send a result (true or false)

What we can do is copy/paste the code of **/books** route and change it.

```javascript
// Replace the GET method by POST
// Reminder: POST in the API world is used to ADD a data
app.post("/books", (request, response) => {
  // TODO: Fill the function

  return response.json({ success: false });
});
```

To fill the function, we need to receive parameters. We will use `body-parser` a new NPM package to treat them efficiently.

```shell
# Install body-parser
$ npm install body-parser
```

To use this package, you will need to import it, then indicate to Express.js that you're using it.
At the beginning of your file, you can edit your code with the following:

```javascript
// Import Express.js
import express from "express";
// Import body-parser (to handle parameters more easily)
import bodyParser from "body-parser";

// This variable defines the port of your computer where the API will be available
const PORT = 3000;

// This variable instantiate the Express.js library
const app = express();

// Indicate to Express.js that you're using an additional plugin to treat parameters
app.use(bodyParser.urlencoded({ extended: true }));
```

We can now go back to your new route!

The first function parameter **request** will be useful to access the **body** of the request. You can do the following to get a parameter: `request.body.parameterName`.

Since we know we need a parameter for the name of the book, I suggest... **name**!

```javascript
app.post("/books", (request, response) => {
  // We get the parameter 'name' from the body
  const bookName = request.body.name;

  // We check if the book list includes the new book
  // If it is, we return 'false'
  if (bookList.includes(bookName)) return response.json({ success: false });

  // Otherwise, we add the new book in the list and return 'true'
  bookList.push(bookName);
  return response.json({ success: true });
});
```

Let's open **http://localhost:3000/books** in your browser! Oh... do you notice that we get the list of books?

An API is different from a typical website. You can't access it with your browser. When you reach a website with your browser, a **GET** request is sent (**GET http://localhost:3000/books**).

Do you remember in the **pre-requirements** when I ask you to install **Postman**?
Postman is the most famous tool to interact with APIs. You will see it's working like a browser but for APIs!

**How to request with Postman:**

When you first open Postman, you should see this dashboard.

![Postman - Dashboard](https://herewecode.io/static/169f38205e6fdf7cd1fd9044e73f1043/b7ae7/postman-dashboard.png)

You can click on the "+" icon to create your first request.

Then, you can enter the URL to request in the corresponding input (**http://localhost:3000/books**). It's equivalent to type in a URL in your browser search bar.

Next to the URL, you can **GET**. It's corresponding to the type of request we are doing. In our case, we want to add a book, so it's a **POST** request. Click on it, and selected **POST**.

![Postman - POST request](https://herewecode.io/static/d384ba6f06ebef36dbb55883142492d0/b7ae7/postman-post-request.png)

Almost everything is ready, but we need to add parameters to our request. To do it, you can click on **the tab "body"**, then **"x-www-form-urlencoded"**.

> **Note:** **"x-www-form-urlencoded"** allows you to send simple text as a parameter.

![Postman - POST request body](https://herewecode.io/static/5090c74065ea521c56f6373c4bb1d31c/b7ae7/postman-post-request-body.png)

To add a parameter, you can do it in the table below the URL search bar.
**"Key"** is your parameter name and **"value"** it's value.

> **Note:** In our case, we want a parameter **name**. `const bookName = request.body.**name**;`

![Postman - POST request body with parameters](https://herewecode.io/static/f3eb02bd97017399eb8360c6ee78f547/b7ae7/postman-post-request-body-with-parameters.png)

Now that you're ready, you can click on the **"Send"** button to see the result of your request!

![Postman - POST request result](https://d33wubrfki0l68.cloudfront.net/d962119f949e4e575333dfe2a711fbf5844430fc/d01ba/static/da5fb07fc4827f1f913e4216a5d487ba/b7ae7/postman-request-result.png)

**Output:**

```json
{
  "success": true
}
```

Try a second time to it the "Send" button.

**Output:**

```json
{
  "success": false
}
```

The output is false as expected because the book already stored in the list.

> **Note:** You can get all books through Postman to check if your new book appears in it. To do it, do the same steps than in **"how to request with postman"**, but choose **GET** as request mode.

## 6. Create a book to delete a book

Now you created a **GET** and a **POST** method the process will always be the same.
In this part, we will create a **DELETE** method on **/books**. We will have one **name** parameter, and the goal of our function will be to delete the book if it's in the list.

```javascript
app.delete("/books", (request, response) => {
  // We get the parameter 'name' from the body
  const bookToDelete = request.body.name;

  // We create a new array with all elements different from the book to delete
  bookList = bookList.filter((book) => book !== bookToDelete);

  // We return the new list
  return response.json({ allBooks: bookList });
});
```

> **Note:** We return the new book list, but you are free to respond something else.

## 7. Create a route to update a book

The last missing thing in your API is the ability to update a book name. The **PUT** method allows you to update data in an API.

**Example:**

**CURRENT:** I add _"Mirocle Morning"_, but the real name is _"Miracle Morning"_. I should delete _"Mirocle Morning"_, then add _"Miracle Morning"_.
**WHAT WE WANT:** I add _"Mirocle Morning"_. I update _"Mirocle Morning"_ to _"Miracle Morning"_.

```javascript
app.put("/books", (request, response) => {
  // We get the parameters 'nameToUpdate' and 'updatedName' from the body
  const bookToUpdate = request.body.nameToUpdate;
  const updatedBook = request.body.updatedName;

  // We search if the book to update is in the list
  const indexOfBookToUpdate = bookList.findIndex(
    (book) => book === bookToUpdate
  );

  // If it is not a book from the list, we return 'false'
  if (indexOfBookToUpdate === -1) return response.json({ success: false });

  // Otherwise, we replace the name and return 'true'
  bookList[indexOfBookToUpdate] = updatedBook;
  return response.json({ success: true });
});
```

You did it! Your first API is functional and you can **get all books** and **add**, **update** or **delete** a book!

## Code is available

If you want to retrieve the complete code to discover it more simply or execute it, it's available on my GitHub.
Here's the link: [https://github.com/gael-thomas/First-API-With-Node-And-Express-example](https://github.com/gael-thomas/First-API-With-Node-And-Express-example)

## Things to remember

**What a route is?**
A route is the complete URL path. For example **"http://localhost:3000/books"**.

**What an endpoint is?**
An endpoint is the end of your URL path. For example if your full URL is **"http://localhost:3000/books"**, your endpoint is **"/books"**.

APIs can have different request methods, but the most used are:

- **GET:** To get a data
- **POST:** To add a data
- **DELETE:** To delete a data
- **PUT:** To update a data

---

If you want more content like this, you can [follow me on Twitter](https://twitter.com/gaelgthomas/), where I tweet about web development, self-improvement, and my journey as a fullstack developer!