Mastering RESTful API Development with Express: Your Step-by-Step Guide
How to use Express to build a JSON API

Mastering RESTful API Development with Express: Your Step-by-Step Guide

Why Build An API?

One of the key advantages of a JSON API is its ability to be reused across a variety of applications and devices. Rather than building an app with server-side rendered pages, you can create routes that deliver and receive JSON data. This makes it possible to integrate your API with front-end web applications, mobile apps, desktop applications, and internet-enabled devices. Furthermore, other developers can use your API to build new applications on top of your platform, much like the apps built around popular social media platforms such as Facebook and Twitter.

Getting Started

  • Create a new empty folder called pizza_api
  • Open your terminal in this pizza_api folder and create a filed called server.js
  • Create a new node project

npm init -y        

  • Install express & nodemon

npm install express nodemon        

  • Update your scripts in package.json

"scripts": {
  "start": "node server.js",
  "dev": "nodemon server.js"
}        

Start Server

To begin with, let's outline the fundamental aspects of our server.js file to ensure that it can successfully run as a server.

////////////////////////
// DEPENDENCIES
/////////////////////////
const express = require("express")

/////////////////////////
// The Application Object
/////////////////////////
const app = express()

/////////////////////////
// Routes
/////////////////////////

// home route that says "hello world" to test server is working
app.get("/", (req, res) => {
    //res.json let's us send a response as JSON data
    res.json({
        response: "Hello World"
    })
})

/////////////////////////
// Listener
/////////////////////////
app.listen(1337, () => console.log("Listening on port 1337"))        

  • Start your server

npm run dev        

  • Navigate to http://localhost:1337/ and see if you get a response. If so, you've successfully created an API!

Let's talk Pizza...

While creating an API that simply returns a "Hello World" message in JSON format may not be very useful, it is still an API nonetheless. Now, let's work on building something more compelling – an API that provides information on our favorite pizzas

We'll be implementing the CRUD (Create, Read, Update, Delete) operations for our pizza API. Since we'll be using a static array, any changes made to the data will be lost if the server is restarted, so it's important to keep that in mind.

The Data

Let's add our array with starter data to server.js below the Application Object.

////////////////////////
// The Data
/////////////////////////

const pizzas = [
    {name: "Margherita", ingredients: ["tomatoes", "mozzarella", "basil"]},
    {name: "Pepperoni", ingredients: ["tomatoes", "mozzarella", "pepperoni"]},
    {name: "Hawaiian", ingredients: ["tomatoes", "mozzarella", "ham", "pineapple"]},
    {name: "Vegetarian", ingredients: ["tomatoes", "mozzarella", "mushrooms", "onions", "peppers"]},
];        
No alt text provided for this image
Code, slice, repeat 🍕💻🔁 #ProgrammerFuel

Index Route

We'll now create an index route that retrieves the list of pizzas and returns it as a JSON response.

// Pizzas Index Route (Send All Pizzas)

app.get("/pizzas", (req, res) => {
    // send the pizzas array as JSON
    res.json(pizzas)
})        

Go to http://localhost:1337/pizzas and test route.

Show Route

Next, we will set up a route for fetching a single pizza. Although it may not be frequently utilized in React applications, as the complete dataset is usually stored in the State and we can access individual items from there, having this option available can be useful.

// Pizzas Show Route (Send One Pizza)

app.get("/pizzas/:index", (req, res) => {
    // send the pizzas array as JSON
    res.json(pizzas[req.params.index])
})        

Go to http://localhost:1337/pizzas/0 and test route.

Create Route

To set up a post route for creating a new pizza, we need to enable the ability to send a JSON body. This can be achieved by using the middleware express.json(), which parses incoming JSON data.

////////////////////////
// The Application Object
/////////////////////////
const app = express()

/////////////////////////
// MIDDLEWARE
/////////////////////////

app.use(express.json())        

Now we can add the post route!

// Pizzas Post Route (Create New pizza

app.post("/pizzas", (req, res) => {

    // push the request body into the array
    pizzas.push(req.body)

    // send the pizzas array as JSON
    res.json(pizzas)
})
)        

Testing the Post Route

It is not possible to test this route in a browser as the browser does not support making POST requests by directly entering a URL in the address bar. However, we can still test this route using Postman!

  • Open postman
  • Open a new tab
  • Set the method to post
  • Set the url to http://localhost:1337/pizzas
  • Add your favorite slice! Choose raw for body and select json for your datatype and send the following:

{
  "name": "New Pizza",
  "ingredients": ["ingredient1", "ingredient2", "ingredient3"]
}        

  • Submit the request and confirm whether you see the new pizza!

The Update Route

We'll create an additional route for updating a pizza.

// Pizzas Update Route

app.put("/pizzas/:index", (req, res) => {

    // replace the pizza at the specified index with the request body
    pizzas[req.params.index] = req.body

    // send the turtles array as JSON
    res.json(pizzas)
})        

  • Make a PUT request to localhost:1337/pizzas/0, Supreme should replace Margherita.

{
    "name": "Supreme",
    "ingredients": [
        "tomatoes",
        "mozzarella",
        "pepperoni",
        "sausage",
        "onions",
        "bell peppers",
        "olives"
    ]
}        

The Delete Route

Let's create a route to delete a pizza, since we're dealing with a simple array we can use the splice method to remove the desired pizza.

// Pizzas delete Route

app.delete("/pizzas/:index", (req, res) => {

    // remove the pizzas at the specifed index
    pizzas.splice(req.params.index, 1)

    // send the pizzas array as JSON
    res.json(pizzas)
})        

send a delete request to localhost:1337/pizzas/0 and Supreme should disappear.

Conclusion

In conclusion, by using Express to only manage the Controllers and Models part of the MVC architecture, the backend development process becomes significantly easier. However, this comes at the cost of making state management in the front-end more complex. Unfortunately, there is no perfect solution to this tradeoff.





Jacek Fleszar

Data Analysts||Programmer||Big Data||Data Science-Enthusiast||Python💢

2y

Very useful 🎺

Ziv Meri

Helping you develop powerful algorithms | Take your first step with C4DYNAMICS

2y

I've just ate meat so I have to wait 6 hours before reading

To view or add a comment, sign in

More articles by Ayelet Hillel

Insights from the community

Others also viewed

Explore topics