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:
- Setup the project
- Initialize your API
- Create your first route
- Create a route to get all books
- Create a route to add a book
- Create a route to delete a book
- 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.
# 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.
# Install Express.js
$ npm install express
Now, if you open your package.json
file, you will see the following lines.
{
"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.
{
/* 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.
// 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:
$ 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.
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.
// 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:
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:
// 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:
{"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.
// 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.
# 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:
// 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!
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.
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.
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.
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**;
Now that you're ready, you can click on the "Send" button to see the result of your request!
Output:
{
"success": true
}
Try a second time to it the "Send" button.
Output:
{
"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.
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".
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
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, where I tweet about web development, self-improvement, and my journey as a fullstack developer!
Top comments (11)
Awesome article, just one thing,
const bookList
should belet
because it is being assigned a new array when a book is deleted.Thank you! 👍😀
Good point, I did it on GitHub, but I forgot to change it in the article. I updated it!
It should be const because Array is an object and reference to the object is not changed.
Read more here
This is absolutely brilliant.
Thank you! 🤩
Cool Node is so easy to learn honestly all front end developers who use javascript should be using Node as well its just natural.
I don't think it's easy for everyone! But indeed, if you're a JS frontend developer, it's good to use because you don't have to learn a new language (again).
I will admit that I did not learn Node after I learned JavaScript. It took me more than a year before I finally decided to look into it. Back then I only cared about front-end development the thought of working on the back-end did not appeal to me that much. But now I'm full-stack so my eyes have been opened and I have grown as a developer.
This posted rekindled my motivation to Backend development
Oh yeah! 🕺 So glad to read that! Keep coding, even if it's hard! The more you will do it, the better you will understand and create quality apps. 😁
Great course to begin working with Node ! Thanks Gaël!