DEV Community

Cover image for Creating a Simple RESTful API with Node.js
Vaishnavi Rawool
Vaishnavi Rawool

Posted on

Creating a Simple RESTful API with Node.js

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

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

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

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

Image description

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

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

Step 8: Create a basic API route in express

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

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

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

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

Code Explanation:

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

Code Explanation:

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

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

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

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

Image description

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!

Top comments (1)

Collapse
 
chirags_ profile image
Chirag Supal

very helpful, thank you!