Page Content

Tutorials

How to build a Rest API with Node.js and Express?

Rest API with Node.js and Express.js

Usually utilising HTTP protocols, a REST API (Representational State Transfer Application Programming Interface) allows various computer systems to interact with one another via the internet. Scalable network programs and online applications, including HTTP APIs, are ideally suited for Node.js, cross-platform JavaScript runtime environment.

With its extensive feature set for developing online apps and HTTP APIs, Express.js is a simple and adaptable Node.js web application framework. Basic web servers can be created with Node.js’s built-in http module, but Express.js makes code easier to maintain and expand by streamlining the process of establishing routes and processing requests. Because of Express’s widespread use and simplicity in building REST APIs and static web servers, many Node.js classes begin with it.

Fundamental to REST APIs, HTTP methods are the kinds of requests you send to the server. For a RESTful system, the most popular techniques are as follows:

  • GET: Used for retrieving data from the server. In Express, you use app.get() for this type of request.
  • POST: Used for sending data to the server, such as submitting form data or creating a new resource. This is handled by app.post() in Express.
  • PUT: Used for updating something on the server, like correcting a misspelling. In Express, you use app.put().
  • DELETE: Used for removing something from the server, such as deleting an item from a list. Express uses app.delete() for this.

Structuring REST APIs

Using Express to structure a REST API entails assigning URLs to particular operations. Routes give a unique combination of a URL path and request method a specified function rather than URL paths to particular files. To request a list of users, for example, use GET /users; to GET a specific user by ID, use GET /users/:id. The variable portion of the URL that may be accessed in Express via req.params.id is indicated by the :id.

In order to prevent a “giant mess” from a single large callback function, Express permits modular applications. One way to do this is by:

  1. Separating route files: express.Router() allows you to construct distinct router instances. Before registering with the main Express application using app.use(router), each router can specify routes for a particular resource (for example, a router for users and another for tasks). This allows your code to be reused and your application to be modular and adaptable.
  2. Model-Routes-Controllers-Services (MRCS) structure: For larger applications, a common architectural pattern is to divide the logic into Models, Routes, Controllers, and Services.
    • Models define the schema of your data.
    • Routes map API paths to Controllers.
    • Routes assign Controllers to API routes. The logic for verifying request parameters, queries, and providing responses with the appropriate HTTP status codes is handled by controllers.
    • Services include database queries that either throw errors or return objects. Code with this structure is more segregated and easier to maintain.

Building Basic CRUD Endpoints

Building CRUD (Create, Read, Update, Delete) API endpoints is quite simple with Express.

  • Create (POST): application.post('/users',…) is used to create a new resource (such as a user). Req.body can be used to read the request body, which is typically JSON, once it has been parsed using express.json() or body-parser middleware. As an illustration, const user = new User(req.body). Following saving, you may receive a success message or the generated object in response.
  • Read (GET):
    • App.get('/users',…) is used to list all resources. Your model (for example, Articles.find()) can be used to retrieve data, which can then be sent as a JSON array using res.send(users) or res.json(users).
    • An individual resource can be retrieved by ID by using app.get('/users/:id',…). Using req.params.id, one may retrieve the ID.
  • Update (PUT/PATCH): app.patch('/users/:id',…) manages requests to change an existing resource using PATCH, which is frequently used with a URL structure like /tasks/:id. To stop users from changing restricted fields, it’s a good idea to validate permitted adjustments. Instead, you can use app.put('/item/:id',…) to replace an item completely.
  • Delete (DELETE): uses app.delete('/users/:id',…) to delete a resource. Methods such as findByIdAndDelete(req.params.id) can be used to eliminate the database entry.

Using Postman

With Postman, you can test your REST API endpoints by sending different HTTP queries. While you’re building your endpoints, it makes debugging them simple.

How to utilise Postman:

  1. Installation: Postman is free and compatible with all OS systems; you can download it from its official website.
  2. Making Requests: To transmit GET, POST, PUT, DELETE, and other HTTP requests, Postman offers an intuitive user interface. The request content (e.g., JSON payload for POST/PUT requests), headers, HTTP method, and URL can all be readily specified.
  3. Inspecting Responses: Following a request, Postman shows the server’s answer, along with the headers, the response body (such as HTML or JSON data), and the status code (e.g., 200 OK, 404 Not Found). This lets you make sure your API is operating as it should.
  4. Environments: Postman environments let you store and reuse variables (such the base URL and authentication tokens) between requests, which makes handling requests and authentication easier.

Node.js and Express.js may be combined to create scalable and reliable RESTful APIs quickly, and Postman and other tools are crucial for testing and debugging at every stage of the development process.

Index