How to create REST API using Node.js and Express?

by Mar 7, 2024IoT Cloud

In the vast landscape of web development, creating a robust API is a fundamental skill. APIs, or Application Programming Interfaces, serve as the communication bridge between different software applications. Today, we’ll embark on a journey to build a simple blog API using Node.js and the popular Express framework.

What is an API?

An API, or Application Programming Interface, is a set of rules and tools that allows different software applications to communicate with each other. It defines the methods and data formats that applications can use to request and exchange information. APIs play a crucial role in enabling the integration of various services and applications, facilitating interoperability and data exchange.

In simpler terms, an API is like a conversation between a client and a server. The client makes requests by following a set of rules, and the server responds with the requested information or action. It’s a way for different programs to talk to each other and exchange data in an organized manner.

Real-Time Example: Weather API

Imagine you’re developing a weather application, but you don’t have the resources to collect and maintain weather data for every location on your own. This is where a Weather API comes into play.

1. API Provider (Server):

There is a Weather API provider (e.g., OpenWeatherMap, Weatherstack) that collects and updates weather information regularly. This provider exposes an API with specific endpoints and data formats.

2. API Consumer (Client):

You are the developer creating a weather application. Instead of collecting and maintaining your weather data, you decide to use a Weather API to get real-time weather information. Maybe you are lazy to collect information and rather use an API!! (jus kidding)

3. How the API Works:

Your weather application sends an HTTP request to the Weather API’s endpoint, specifying the location (e.g., city or coordinates). The Weather API processes the request, retrieves the current weather data for the specified location, and formats it according to the API’s standards. The API then sends the formatted data back to your application as an HTTP response.

4. Integration in Your Weather App:

Your weather application parses the received data and uses it to display the current weather conditions, temperature, humidity, etc. Users of your application get real-time weather updates without your app having to manage the entire database of weather information.

In this example, the Weather API acts as a bridge between your weather application and the weather data provider, allowing your app to access and display real-time weather information without the complexity of managing the entire data infrastructure. This illustrates how APIs streamline communication and collaboration between different software components.

In this blog, we will set up a new node.js project. Open your terminal and follow the commands! These following commands are to set up a node project.

Installing Express

Now, we will install express in this project. According to the documentation, Express is a Fast, unopinionated, minimalist web framework for Node.js.

Set up the Express App

In your project, create a file “index.js”, and lets lay the foundation for your Express app.

const express = require("express");
const app = express();
const port = 3000;

app.use(express.json());

// Routes will go here

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

When you run the above code, you will notice that the server runs on the localhost 3000. That’s where the port is mentioned. The code imports the Express framework and assigns it to the variable express. The express() function creates an instance of the Express application. This app object is the central piece of an Express application, and it is used to define routes, middleware, and handle HTTP requests and responses.

The app.use() function is setting up middleware for the Express application. In this case, it’s using the express.json() middleware, which parses incoming JSON requests. It makes the parsed JSON data available in req.body for further processing in your routes.

The comment, “// Routes will go here,” indicates that you should define your routes between the app.use(express.json()) line and the app.listen() line. Routes define how your server responds to different HTTP requests, such as GET, POST, PUT, or DELETE, for specific endpoints.

Now, we will see how to set up such a CRUD operation in this code.

Before that, we should know the basics of REST API:

For now, we can know the most important technical stuff.

A RESTful API (Representational State Transfer) is an architectural style for designing networked applications. REST is often used in the context of web services to create scalable, lightweight, and maintainable systems. Here are some key concepts and principles associated with RESTful APIs:

Resources: In REST, everything is considered a resource. A resource can be an object, data, or service that can be identified by a unique URI. Examples of resources include user profiles, products, articles, etc. In our code, we have described how to access product value and ids.

HTTP Methods (Verbs): RESTful APIs use standard HTTP methods for communication. The primary HTTP methods used in REST are:

  • GET: Retrieve a resource.
  • POST: Create a new resource.
  • PUT: Update an existing resource (replace).
  • PATCH: Update an existing resource (partially).
  • DELETE: Remove a resource.

URIs (Uniform Resource Identifiers): Resources are identified using URIs. Each resource should have a unique URI that clients can use to interact with it.

For example: /api/users, /api/products/123.

Status Codes: HTTP status codes are used to indicate the success or failure of a request. Common status codes include 200 (OK), 201 (Created), 204 (No Content), 400 (Bad Request), 404 (Not Found), and 500 (Internal Server Error).

Security: RESTful APIs can use standard HTTP security mechanisms such as HTTPS for secure communication, authentication using API keys or tokens, and authorization based on user roles.

These are the important key concepts to know about RESP API. Now, we will dive into the code. This code is the basic CRUD operation just to access, update, post or delete the products in in-memory.

Tips for node.js: Use nodemon to avoid restarting your server.

const express = require("express");
const app = express();
const port = 3000;

app.use(express.json());

const products = [
  { id: 1, name: "Ceramic" },
  { id: 2, name: "Resin" },
  { id: 3, name: "Paraffin Wax" },
];

// Get all products
app.get("/api/products", (req, res) => {
  res.json(products);
});

//get specific product by id

app.get("/api/products/:id", (req, res) => {
  const productId = parseInt(req.params.id);
  const item = products.find((item) => item.id === productId);
  if (!item) {
    return res.status(404).json({ error: "Item not found." });
  }
  res.json(item);
});

//post products
app.post("/api/products", (req, res) => {
  const { name } = req.body;
  if (!name) {
    return res.status(404).json({ error: "Name is required." });
  }
  const newItems = { id: products.length + 1, name };

  products.push(newItems);
  res.status(201).json(newItem);
});

//update products

app.put("/api/products/:id", (req, res) => {
  const itemId = parseInt(req.params.id);
  const item = products.find((item) => item.id === itemId);

  if (!item) {
    return res.status(404).json({ error: " product not found." });
  }
  const { name } = req.body;
  if (item) {
    item.name = name;
  }
  res.status(200).json(item);
});

//delete products

app.delete("/api/products/:id", (req, res) => {
  const itemId = parseInt(req.params.id);
  const item = products.findIndex((item) => item.id === itemId);

  if (item == -1) {
    return res.status(404).json({ error: " product not found." });
  }
  const deleteProduct = data.splice(item, 1)[0];
  res.status(200).json(deleteProduct);
});

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

Verify using Postman

Test Your CRUD API: Run your server with node app.js and use a tool like Postman or curl to test your API endpoints:

  • GET (All): http://localhost:3000/api/products
  • GET (Specific): http://localhost:3000/api/products/1
  • POST: http://localhost:3000/api/products (with JSON payload)
  • PUT: http://localhost:3000/api/products/1 (with JSON payload)
  • DELETE: http://localhost:3000/api/products/1

The best alternative for Postman is also Kong Insomnia, which is a collaborative open source API development platform that makes it easy to build high-quality APIs — without the bloat and clutter of other tools.

This example provides a simple in-memory CRUD API using Express. Depending on your use case, you may want to replace the in-memory data store with a database and add additional features such as validation, authentication, and error handling.

In our next blog, we can see how to integrate a database like SQL and MongoDB.

Creating a multiplication Skill in Alexa using python

Written By Monisha Macharla

Hi, I'm Monisha. I am a tech blogger and a hobbyist. I am eager to learn and explore tech related stuff! also, I wanted to deliver you the same as much as the simpler way with more informative content. I generally appreciate learning by doing, rather than only learning. Thank you for reading my blog! Happy learning!

RELATED POSTS

Creating REST API CRUD with Node.js, Express and MongoDB

Creating REST API CRUD with Node.js, Express and MongoDB

In our previous blog, we explored the fundamentals of creating a REST API with in-memory CRUD operations using Node.js and Express. Now, we're taking a significant step forward by integrating our product data with a database. This transition is pivotal for achieving...

APIs Vs. Microservices: What is the difference?

APIs Vs. Microservices: What is the difference?

You've probably heard two extravagant terms thrown around when discussing software design and integrations: APIs and microservices. Both topics are important in web application development and design nowadays, and their applications overlap. In this article, we will...

Understanding Salesforce IoT and Its Importance

Understanding Salesforce IoT and Its Importance

In this post, we are going to discuss Salesforce IoT. All across the globe, people are connecting to the Internet to access information, communicate with other people, and do business. But it's not just people that are using the Internet: objects use it too....

Best IoT IDEs For Successful IoT Products

Best IoT IDEs For Successful IoT Products

IoT IDEs are the essential tools that we need in developing our IoT projects. They give us the pathway to connect our Hardware and Software and do magical things using IoT. Consequently, they are useful. IoT is the next big thing in the world. It has taken the whole...

Top 5 Databases to store data of IoT applications

Top 5 Databases to store data of IoT applications

Databases for IoT applications The Internet of Things (IoT) produces massive quantities of data, such as streaming data, time-series data, RFID data, and sensory data, among other things. The use of a database is needed for efficient data management. The existence of...

An overview of Google Cloud Platform for IoT

An overview of Google Cloud Platform for IoT

The cloud technologies have revolutionised the niche of Internet of Things. The cloud technologies for Internet of Things offer a one stop solution for securely connecting devices and securely communicating between the devices. It also offers the tools to process the...

VIDEOS – FOLLOW US ON YOUTUBE

EXPLORE OUR IOT PROJECTS

IoT Smart Gardening System – ESP8266, MQTT, Adafruit IO

Gardening is always a very calming pastime. However, our gardens' plants may not always receive the care they require due to our active lifestyles. What if we could remotely keep an eye on their health and provide them with the attention they require? In this article,...

How to Simulate IoT projects using Cisco Packet Tracer

In this tutorial, let's learn how to simulate the IoT project using the Cisco packet tracer. As an example, we shall build a simple Home Automation project to control and monitor devices. Introduction Firstly, let's quickly look at the overview of the software. Packet...

All you need to know about integrating NodeMCU with Ubidots over MQTT

In this tutorial, let's discuss Integrating NodeMCU and Ubidots IoT platform. As an illustration, we shall interface the DHT11 sensor to monitor temperature and Humidity. Additionally, an led bulb is controlled using the dashboard. Besides, the implementation will be...

All you need to know about integrating NodeMCU with Ubidots over Https

In this tutorial, let's discuss Integrating NodeMCU and Ubidots IoT platform. As an illustration, we shall interface the DHT11 sensor to monitor temperature and Humidity. Additionally, an led bulb is controlled using the dashboard. Besides, the implementation will be...

How to design a Wireless Blind Stick using nRF24L01 Module?

Introduction Let's learn to design a low-cost wireless blind stick using the nRF24L01 transceiver module. So the complete project is divided into the transmitter part and receiver part. Thus, the Transmitter part consists of an Arduino Nano microcontroller, ultrasonic...

Sending Temperature data to ThingSpeak Cloud and Visualize

In this article, we are going to learn “How to send temperature data to ThingSpeak Cloud?”. We can then visualize the temperature data uploaded to ThingSpeak Cloud anywhere in the world. But "What is ThingSpeak?” ThingSpeak is an open-source IoT platform that allows...

Amaze your friend with latest tricks of Raspberry Pi and Firebase

Introduction to our Raspberry Pi and Firebase trick Let me introduce you to the latest trick of Raspberry Pi and Firebase we'll be using to fool them. It begins with a small circuit to connect a temperature sensor and an Infrared sensor with Raspberry Pi. The circuit...

How to implement Machine Learning on IoT based Data?

Introduction The industrial scope for the convergence of the Internet of Things(IoT) and Machine learning(ML) is wide and informative. IoT renders an enormous amount of data from various sensors. On the other hand, ML opens up insight hidden in the acquired data....

Smart Display Board based on IoT and Google Firebase

Introduction In this tutorial, we are going to build a Smart Display Board based on IoT and Google Firebase by using NodeMCU8266 (or you can even use NodeMCU32) and LCD. Generally, in shops, hotels, offices, railway stations, notice/ display boards are used. They are...

Smart Gardening System – GO GREEN Project

Automation of farm activities can transform agricultural domain from being manual into a dynamic field to yield higher production with less human intervention. The project Green is developed to manage farms using modern information and communication technologies....