Node.js REST Client
node-rest-client is a versatile Node.js library for interacting with RESTful APIs, designed to simplify HTTP/HTTPS requests. It offers features such as transparent handling of HTTP/HTTPS connections, basic authentication, and support for common HTTP methods (GET, POST, PUT, DELETE, PATCH), with the ability to define custom methods. A key differentiator is its capability to register remote API operations as reusable client methods, streamlining code and promoting reuse. The library also manages dynamic path and query parameters, request headers, provides improved error handling, supports compressed responses (gzip, deflate), follows redirects (via `follow-redirects`), and allows for custom request serializers and response parsers (with JSON and XML included by default). The current stable version is 3.1.1. Release cadence is not strictly scheduled, but the project shows active development with recent major and minor updates.
Common errors
-
TypeError: client.post is not a function
cause Attempting to call `post`, `put`, or `patch` methods without providing the necessary `args` object.fixEnsure the second argument to `client.post`, `client.put`, or `client.patch` is always an `args` object, even if empty, before the callback function. -
Error: Response data is not parsed correctly. Expected JSON but received raw string/buffer.
cause The default response parsers (JSON, XML) do not match the `Content-Type` header of the API response, or the response contains malformed data.fixVerify the `Content-Type` header sent by the API. If it's a custom type or not correctly handled, configure custom response parsers using `client.registerParser()` or `new Client({ mimetypes: { /* ... */ } })`. -
ReferenceError: require is not defined in ES module scope
cause Attempting to use `require('node-rest-client')` in a Node.js environment configured for ECMAScript Modules (ESM) (e.g., `"type": "module"` in `package.json`).fixFor ESM projects, use dynamic `import('node-rest-client')` and then access the `Client` class, e.g., `const { Client } = await import('node-rest-client');`. Alternatively, ensure your file is treated as CommonJS (e.g., `.cjs` extension or no `"type": "module"` in `package.json`).
Warnings
- breaking With the introduction of v3.0.0, the library prefixed all internal methods with a `$` to prevent potential name clashes with custom registered methods. If you were directly accessing or overriding internal methods in versions prior to v3, your code will break.
- gotcha When performing POST, PUT, or PATCH requests, the 'Content-Type' header must be explicitly set in the `args.headers` parameter. Failing to do so will result in the request body not being properly sent or parsed by the remote API.
- gotcha For responses other than default JSON or XML, or if a different encoding is used, you may need to configure custom response parsers or specify `mimetypes` in the `Client` options. Otherwise, the `data` callback parameter might contain unparsed raw data or incorrect types.
Install
-
npm install node-rest-client -
yarn add node-rest-client -
pnpm add node-rest-client
Imports
- Client
import { Client } from 'node-rest-client';const Client = require('node-rest-client').Client; - Client (full module)
import nodeRestClient from 'node-rest-client';
const nodeRestClient = require('node-rest-client'); const Client = nodeRestClient.Client; - Custom Method Registration
client.myMethod(function(data, response){ /* ... */ });client.registerMethod('myMethod', 'http://example.com/api', 'GET'); client.methods.myMethod(function(data, response){ /* ... */ });
Quickstart
const Client = require('node-rest-client').Client;
const client = new Client();
// Example: Simple HTTP GET request
client.get("https://jsonplaceholder.typicode.com/posts/1", function (data, response) {
// parsed response body as js object
console.log('GET Response Data:', data);
// raw response
console.log('GET Response Status:', response.statusCode);
});
// Example: HTTP POST request with JSON data and headers
const args = {
data: { title: 'foo', body: 'bar', userId: 1 },
headers: { "Content-Type": "application/json" }
};
client.post("https://jsonplaceholder.typicode.com/posts", args, function (data, response) {
console.log('POST Response Data:', data);
console.log('POST Response Status:', response.statusCode);
});