REST APIs use HTTP methods (such as GET, POST, PUT, DELETE) to define actions that can be performed on resources. These methods align with CRUD (Create, Read, Update, Delete) operations, which are used to manipulate resources over the web. The HTTP GET method is used to read (or retrieve) a representation of a resource. In the safe path, GET returns a representation in XML or JSON and an HTTP response code of 200 (OK). In an error case, it most often returns a 404 (NOT FOUND) or 400 (BAD REQUEST). The POST method is commonly used to create new resources. It is often used to create subordinate resources related to a parent resource. Upon successful creation, the server returns HTTP status 201 (Created) along with a Location header pointing to the newly created resource. PUT is an HTTP method used to update or create a resource on the server. When using PUT, the entire resource is sent in the request body, and it replaces the current resource at the specified URL. If the resource doesn’t exist, it can create a new one. PATCH is an HTTP method used to partially update a resource on the server. Unlike PUT, PATCH only requires the fields that need to be updated to be sent in the request body. It modifies specific parts of the resource rather than replacing the entire resource. It is used to delete a resource identified by a URI. On successful deletion, return HTTP status 200 (OK) along with a response body. Now let’s create a REST AP and perform the various HTTP operations. npm init npm install express To install Nodemon, use the npm command npm install -g nodemon globally within your project. 1) Node.js: JavaScript runtime environment.
2) Express.js: Framework to build APIs easily.
3) fs (File System module): For logging API requests to a file (log.txt). Postman => Postman is an API platform that helps developers build, test, and document APIs.
GET /users: This route fetches the list of users (or mock data in this case).
POST /users: This route accepts JSON data from the client to create a new user.
PUT /users/:id: This route updates the information of a user based on the user ID provided in the URL.
DELETE /users/:id: This route deletes a user with the specified ID.
Send a GET request to http://localhost:8000/api/users.
Response: All users from MOCK_DATA.json.
Example: http://localhost:8000/api/users/2.
Response: Specific user details.
Send a POST request with body (form-data or x-www-form-urlencoded).
Response: {status: "pending"}
Send a PATCH request with body to update user info.
Response: {status: "pending"}
Send a DELETE request to remove a user.
Response: {status: "pending"}
✏️ Postman is very useful here because you can easily create different types of requests (GET, POST, PATCH, DELETE) and test how your server behaves.
Every request made to the server (through Postman/browser) is automatically logged in a log.txt file.The log includes:
Timestamp
IP Address
HTTP Method (GET, POST, etc.)
Request Path