Creating a Simple RESTful API with Node.js
Tags: webdev, rest, node, express
Published: 2024-06-19 17:54:05

## What is an API ?

An API, or application programming interface, is a set of rules or protocols that enables software applications to communicate with each other to exchange data, features and functionality.It’s useful to think about API communication in terms of a request and response between a client and server. The application submitting the request is the client, and the server provides the response. The API is the bridge establishing the connection between them.

## What are the types of APIs?

Some of the most common type of APIs are:


1. **RESTful APIs**: Use standard HTTP methods like GET, POST, PUT, DELETE to interact with resources identified by URLs. They are stateless and follow the principles of REST for scalability and simplicity in client-server communication.

2. **SOAP APIs**: Employ XML-based messaging and typically use protocols like HTTP or SMTP. They adhere to a strict messaging format and rely on a contract (WSDL) for defining endpoints and operations, making them suitable for complex integrations requiring strong reliability and security measures.

## What is REST ?

REST stands for Representational State Transfer. It's an architectural style for designing networked applications. Here’s a simple explanation:

Imagine you're in a restaurant. When you want to order food, you ask the waiter for the menu, choose your dishes, and tell the waiter your order. REST works similarly in the digital world:

- Resources: Think of these as items on the menu — they can be data or functionality (like getting information or saving data).

- HTTP Methods: These are like actions you can take with your order, such as GET (to retrieve data), POST (to add new data), PUT (to update data), DELETE (to remove data).

- URLs: Just like how you tell the waiter where to bring your food, URLs specify where to find or interact with resources.

RESTful APIs use these concepts to allow different systems to communicate over the internet, making it easier for computers to share and use information effectively.

Know everything about REST -> https://restfulapi.net/


##  How to create REST APIs in Node.js ?

**- Tools Required**
  

1. Node.js (Node.js is a runtime environment that allows developers to run JavaScript code outside of a web browser, enabling server-side scripting and building scalable network applications)

2. Express.js (Express.js is a minimalist Node.js web framework with features for routing, middleware support, and simplified handling of HTTP requests and responses.)

3. VS Code (Code Editor) or any other editor of your choice


**Step 1:** Install latest versions of above mentioned software

**Step 2:** Creating a Node Project

- Create a new folder called **node-rest-apis**
-  When installing Node.js, **npm**, the package manager, is also installed, that helps us create a new node project
- Open the integrated terminal within VS Code with the following command -> **Ctrl + `**
- Enter the following command -> **npm init**
- Follow the prompt -> npm init will ask you for information such as the project name, version, description, entry point (usually index.js), test command, repository URL, author information, and license. You can either fill out these details or simply press Enter to accept the default values.


**Step 3:** Install express with the help of npm: **npm install express**


![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n6sf0c6oycp5emgokgne.png)


**Step 4:** Create a file named **index.js** file (you may give it any name of your choice)


**Step 5:** Overview of the files/folders created

- package.json: package.json file stores metadata about your project and its dependencies. Whenever we install new dependencies, they are automatically added to the dependencies section of the package.json file in our Node.js project

- node_modules: This directory houses all the dependencies that your project requires. These dependencies are installed via npm or yarn and are listed in package.json.

- index.js : This file usually serves as the entry point to your application. It initializes your application, sets up configurations, and may start the server if it's a web application.


**Step 6:** Install nodemon **npm install nodemon**


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xq4pg7u5r40r91abdmvo.png)

Nodemon is a utility tool for Node.js that helps in development by automatically restarting the Node application when changes are detected in the codebase. This eliminates the need to manually stop and restart the server after every code change, thus speeding up the development workflow.

Make changes to the start script and run the server using the following command : **npm start**


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/057fyluh9jwjddtyowyf.png)


**Step 7:** Let’s start by creating a node server


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dtvizld3hrevuwmosg9e.png)

Code explanation:

- require('express'): Imports the Express module.

- const app = express(): Creates an instance of the Express application.

- const port = 3000: Specifies the port number where the server will listen for incoming requests.

- app.listen(port, ...): Starts the Express server on the specified port (3000 in this case) and logs a message to the console once the server is running.

For running your application add the following start script in package.json:


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/opz1tk887tkcbftolzxb.png)


You can you run your application with the following command: **node index.js**


![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g53tjagzdo8uc0kwbjo3.png)


**Step 8:** Create a basic API route in express


![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5hujjb4w66b3q09sorf3.png)

Defines a route handler for the GET request at **/test**. When a GET request is made to /test, it sends back a JSON response { message: 'This is a sample API route' }


**Step 9:** Testing the API using Postman

Postman is a collaborative platform for API development that simplifies the process of designing, testing, and debugging APIs.

The API gives a successful response


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6g9elsleoxuomo7iwl1q.png)


**Step 10**: Let’s organize the code in a MVC (Model, View, Controller) like pattern

Create controllers, services, routes, models folder in the root directory


**Step 11:** Create a file name **user.model.js** under models folder

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rb3r7xbhj5w37cmdt238.png)

These functions mimic basic CRUD (Create, Read, Update, Delete) operations commonly performed on user data in applications. Other CRUD operations like create, update, and delete could be added as needed to complete the CRUD functionality.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yiy5mju3usukp2oriewl.png)


**Step 12:**  Create a file name **user.service.js** under services folder

The service files have all the business logic implemented. For eg: all the users related CRUD operations will go inside this file


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7cflww9ymardpa6l0li1.png)

Code Explanation:

- Import the User model to interact with user data

- Call getUsers and getUsersById methods to perform corresponding operations

- Each method calls methods from model layer. In a real-time project this would include operations performed using a ORM (Object Relationship Mapper). Find more on ORMs here : https://medium.com/@rishu__2701/node-js-database-magic-exploring-the-powers-of-sequelize-orm-a22a521d9d9d


**Step 13:**  Create a file name **user.controller.js** under controllers folder

In your controllers , you would import and use the service methods to handle HTTP requests


![](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/17wsym3y75gosfowwbsq.png)

Code Explanation:

-Import respective service function within the controller file, in our case **user.service.js** within **user.controller.js**

- Define route handlers getAllUsers and getUserById

- Within getAllUsers we are retrieving all user data and sending it as a response with a HTTP status 200. In scenarios where database operations are involved, the data retrieval might fail. In that case, the response needs to be sent accordingly with a status 500.

- getUserById(), finds userId from request params. Find more on request params https://www.geeksforgeeks.org/difference-between-req-query-and-req-params-in-express/

- Send user data with status 200 on successful response

- Send 404 if User is not found

- More on HTTP status codes here https://developer.mozilla.org/en-US/docs/Web/HTTP/Status


**Step 14:**  Create a file name **user.routes.js** under routes folder

**user.routes.js** is typically a file where you define and configure all your application routes using Express Router. Here’s how you can structure and explain a routes.js file:


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b60lbwuyf2x9aqh5nl1z.png)


**Step 15:** Advantages of following this code pattern

- Separation of Concerns: The service layer (user.service.js) encapsulates business logic and serves as an intermediary between controllers and models.

- Reusability: Services can be reused across different parts of the application, promoting code reuse and maintaining DRY (Don't Repeat Yourself) principles. In the scenarios where multiple services need to be called together, a manager file can be created (eg: user.manager.js) that imports all the required services and calls them wherever required. Manager file in turn needs to be imported in controller file.

- Modularity: Each layer (models, services, controllers) has a distinct responsibility, making the application easier to understand, test, and maintain.

- Mock Data: In real-world applications, you would replace the mock data and methods in the model (User.js) with actual database interaction using libraries like Mongoose, Sequelize, etc.


**Step 16:** Mounting routes.js in app.js


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tvs6m6vfb50udj20alft.png)


In your main application file (e.g., index.js), you would integrate routes.js by mounting the router using app.use().

const usersRoute = require('./routes/user.route'); Import the routes.js file.

app.use('/users, routes);: Mount the router at the / users prefix. All routes defined in routes.js will be accessible under / users (e.g., / users /:id, / users /:id/likes, etc.


**Step 17:** Test APIs with Postman


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zgexbuodx2iu0fwekxm6.png)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/li8a9v2jxmze7i64nydg.png)

More Resources on REST APIs

HTTP Verbs -> https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods

REST naming conventions -> https://restfulapi.net/resource-naming/

API Documentation -> https://swagger.io/blog/api-documentation/what-is-api-documentation-and-why-it-matters/


Conclusion:

In summary, REST APIs are essential for modern web development, providing a standardized way for clients and servers to communicate efficiently. Node.js with Express.js offers a powerful framework for creating RESTful APIs, enabling developers to build scalable and maintainable backend systems.

By leveraging Node.js's non-blocking architecture and Express's simplicity, developers can quickly create robust API endpoints for various applications. Understanding these technologies ensures you can deliver efficient, secure, and adaptable backend solutions that meet current and future needs in web development.

Follow for more insightful content on web development and stay updated with the latest tips and tutorials. See you next week with more valuable insights!