DEV Community

Cover image for Simple Node and Express REST API
RedEyeMedia⭕
RedEyeMedia⭕

Posted on

Simple Node and Express REST API

Learn by example how to make a simple API that has two endpoints.

What we will make in this tutorial:

  • simple server running locally on your computer
  • using mocked data for simplicity
  • creating endpoints that we will call to change our data
  • use Postman to query our endpoints

Tutorial on YouTube:

The Code:

const express = require("express");
const bodyParser = require("body-parser");

const app = express();
app.use(bodyParser.json());
const port = 3001;

const customers = [
  { firstName: "John", lastName: "Smith" },
  { firstName: "Harry", lastName: "Potter" },
  { firstName: "Jack", lastName: "Sparrow" },
];

app.get("/customerlist", (req, res) => {
  res.send(customers);
});

app.post("/customer", (req, res) => {
  console.log("req.body: ", req.body);
  const newCustomer = req.body;
  customers.push(newCustomer);
  res.send("Customer added.");
});

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

Enter fullscreen mode Exit fullscreen mode

So let's first talk about the data we will be working with. Its simply an array of objects, with a couple of key/value pairs. First and last name. Feel free to make as many creative additions as you'd like here.
The data:

const customers = [
  { firstName: "John", lastName: "Smith" },
  { firstName: "Harry", lastName: "Potter" },
  { firstName: "Jack", lastName: "Sparrow" },
];
Enter fullscreen mode Exit fullscreen mode

Now let's just take a look at what is the essential part of our server. The boilerplate code that needs to be there for our server to run.
Boilerplate code for the server to run:

const express = require("express");
const bodyParser = require("body-parser");

const app = express();
app.use(bodyParser.json());
const port = 3001;

app.listen(port, () => {
  console.log(`Example app listening at http://localhost: ${port}`);
Enter fullscreen mode Exit fullscreen mode

So basically we need to import express and body parser. Express because it is the framework we use on top of nodejs. Bodyparser so that we can do POST requests and change our data. We set a port so it is open for running queries through it in Postman, and we say listen to that port. Most of this is done with the app variable. Which has some important properties on it, like use and listen.

What we then do is add our endpoints.

What are endpoints?

Endpoints are dedicated spaces under your projects URL that you can visit with a certain request, be it a GET- or a POST-request, and have something happen. The most useful thing to have happen is manipulating the data in a logical way. We like to read, write, update and delete our data, depending on the scenario. These actions corresponds to doing CRUD operations within our RESTful API. And what does all that mean? A RESTful API is a backend service designed in a way that follows a certain pattern we call REST. It's not that easy to get a straight answer to what exactly that entails, when asking google, and it gets pretty technical. CRUD operations on the other hand is more straight forward. Its and acronym which stands for Create, Read, Update and Delete. Doing those operations are usually speaking generally, what you want your API to be able to do.

So back to endpoint. If you create a GET endpoint in your API, it's purpose is usually to get data, or Read data from the database. In the same way, a POST route usually creates new data in the database when called. The thing is you can't just visit the post route in your browser and expect it to get called. You need to explicitly make it a POST request. That's why we use Postman!

image

So our first endpoint just responds with our data, where res stands for response. And the thing that is sent back to us is the customer list called customers. So when calling this endpoint in Postman we would get the list back as a response.

app.get("/customerlist", (req, res) => {
  res.send(customers);
});
Enter fullscreen mode Exit fullscreen mode

image

Lastly we have the POST route which adds one customer to the customer list. Because this is just mocked data we can use simple array manipulation here with customers.push(newCustomer) to add a new customer to the object array.

app.post("/customer", (req, res) => {
  console.log("req.body: ", req.body);
  const newCustomer = req.body;
  customers.push(newCustomer);
  res.send("Customer added.");
});
Enter fullscreen mode Exit fullscreen mode

Conclusion

This is probably one of the easier APIs you can make with Node and Express, but it covers the most basics concepts. And with everything being in the same file I was hoping it would be easier to connect the dots. A natural next step here could be to expand the endpoints to include Update and Delete requests, so you can update and delete objects in the array. You could also change the mocked data to go directly to a database.

I hope you got something from this. Later I'll maybe write an article that does basically the same just that it is connected to Mongodb Atlas.

Cheers!

Follow and support me:

I am especially grateful for subscriptions to my YouTube channel. And if you want to follow me on Twitter, or just give some feedback that's awesome too!

📺 YouTube

🐧 Twitter

I try to get out new web dev content on Youtube every week, and sometimes I write articles like this one.
Hope you enjoy!

Top comments (0)