How to Create RESTful API with Express

  • What is Express and why we use it?
  • Express is a minimal node.js framework, a higher level of abstraction.
  • Express contains a very robust set of features: complex routing, easier handling of requests and responses, middleware, server-side rendering, etc.
  • Express allows for rapid development of node.js applications: we don’t have to re-invent the wheel.
  • Express makes it easier to organize our application into the MVC architecture.
  • Downloading the Project from Github

Create a folder named ‘API’ and download the source code from the provided link.

https://github.com/oguzhanpeker/rest-api.git

  • Installing the Node Modules

To install the necessary Node.js modules, open the terminal in VS Code and execute the command provided.

npm install
  • Running the Application

To initiate the application, run the given command in the terminal.

npm run start
  • How is the REST API architecture?

REST (Representational State Transfer) is an architectural style for designing networked applications, primarily web services. It relies on stateless, client-server communication, typically over HTTP. Here’s an overview of REST API architecture and its key components:

Key Principles of REST API Architecture:

  1. Stateless:
    • Each request from the client to the server must contain all the information needed to understand and process the request. The server does not store any client context between requests.
  2. Client-Server:
    • The client and server are independent of each other. The client handles the user interface and user experience, while the server manages data storage and business logic.
  3. Uniform Interface:
    • REST APIs have a uniform interface, which simplifies and decouples the architecture. This includes:
      • Resource Identification: Each resource is identified by a unique URI (Uniform Resource Identifier).
      • Resource Manipulation Through Representations: Resources can be manipulated using their representations (typically JSON or XML).
      • Self-Descriptive Messages: Each request and response should contain enough information to describe how to process the message.
      • Hypermedia as the Engine of Application State (HATEOAS): Clients interact with the application entirely through hypermedia provided dynamically by application servers.
  4. Cacheable:
    • Responses from the server can be explicitly marked as cacheable or non-cacheable, improving scalability and performance by reducing the need for repeated data fetching.
  5. Layered System:
    • A client cannot ordinarily tell whether it is connected directly to the end server or an intermediary along the way. Intermediary servers can improve system scalability by enabling load balancing and shared caches.
  6. Code on Demand (Optional):
    • Servers can temporarily extend or customize the functionality of a client by transferring executable code.

Components of REST API Architecture:

  1. Resources:
    • Everything is a resource (e.g., users, products, orders). Each resource is identified by a URI. For example, /users, /products, /orders.
  2. HTTP Methods:
    • REST APIs use standard HTTP methods to perform operations on resources:
      • GET: Retrieve a resource or a collection of resources.
      • POST: Create a new resource.
      • PUT: Update an existing resource or create a new resource if it does not exist.
      • PATCH: Partially update an existing resource.
      • DELETE: Remove a resource.
  3. Endpoints:
    • Endpoints are specific URLs where the API can be accessed by the clients. Each endpoint corresponds to a different resource and supports specific HTTP methods.
  4. Headers:
    • HTTP headers are used to pass metadata between the client and server. Common headers include Content-Type (e.g., application/json), Authorization, and Accept.
  5. Status Codes:
    • HTTP status codes in the response indicate the result of the HTTP request:
      • 200 OK: The request was successful.
      • 201 Created: A new resource was successfully created.
      • 204 No Content: The request was successful, but there is no content to send in the response.
      • 400 Bad Request: The request was malformed or invalid.
      • 401 Unauthorized: Authentication is required and has failed or has not yet been provided.
      • 403 Forbidden: The server understood the request but refuses to authorize it.
      • 404 Not Found: The requested resource could not be found.
      • 500 Internal Server Error: The server encountered an unexpected condition.
  6. Representations:
    • Resources are typically represented in JSON or XML format. A representation of a resource is the state of that resource at a given point in time, expressed in a format that can be transmitted and understood by the client and server.

Example of a RESTful API:

Consider a simple RESTful API for managing users.

  • Endpoint: /users
    • GET /users: Retrieve a list of users.
    • POST /users: Create a new user.
  • Endpoint: /users/{id}
    • GET /users/{id}: Retrieve a specific user by ID.
    • PUT /users/{id}: Update a specific user by ID.
    • DELETE /users/{id}: Delete a specific user by ID.

Example Request and Response:

Request:

vbnetCopy codeGET /users/1 HTTP/1.1
Host: api.example.com
Accept: application/json

Response:

jsonCopy codeHTTP/1.1 200 OK
Content-Type: application/json

{
  "id": 1,
  "name": "John Doe",
  "email": "john.doe@example.com"
}

This response includes the user’s details in a JSON format, with the status code 200 OK indicating a successful request.

By adhering to these principles and components, RESTful APIs can be designed to be scalable, maintainable, and easy to use, allowing clients to interact with server resources in a consistent and predictable manner.

  • Testing the Application

In this application, the example JSON data file ‘tours-simple.json’ is located in the ‘dev-data’ folder within the project directory. The ‘tourController.js’ file in the ‘controllers’ folder will access this file, and the ‘tourRoutes.js’ in the ‘routes’ folder will manage the HTTP requests.

  • Endpoint: /tours
    • GET /tours: Retrieve a list of tours.
    • POST /tours: Create a new tour.
  • Endpoint: /tours/
    • GET /tours/{id}: Retrieve a specific tour by ID.
    • PATCH /tours/{id}: Update a specific tour by ID.
    • DELETE /tours/{id}: Delete a specific user by ID.

To test HTTP requests, a third-party application called ‘Postman’ is required, which can be downloaded from here.

  1. Get All Tours

Launch Postman and use the GET method to send a request to the specified URL.

127.0.0.1:3000/api/v1/tours

You will receive a list of all the tours contained in the ‘simple-data.json’ file.

2. Create a New Tour

Utilize the POST method with the same URL and include the following JSON data in the body (raw).

127.0.0.1:3000/api/v1/tours

{
    "name": "Test Tour",
    "duration": 10,
    "difficulty": "easy",
    "price": 1500
}

You will receive a success message, and the new tour will be listed along with its ID number.

Send the GET method once more to check if the new tour has been listed.

3. Get a Tour with ID

For example, to retrieve the tour with ID=2, we need to send a GET request to the following URL.

127.0.0.1:3000/api/v1/tours/2

4. Update the Tour

Let’s update the new tour’s price we just created and change it to 2000. We need to use PATCH method with following URL.

127.0.0.1:3000/api/v1/tours/9

Add the following JSON code into the body of request.

{
    "price": 2000
}

5. Delete the Tour

Let’s delete the new tour that we created for testing (ID=9). We need to use DELETE method with following URL.

127.0.0.1:3000/api/v1/tours/9