HTTP Methods
The BBREClient class provides seven convenience methods that simplify
common HTTP operations: get(), post(), put(),
delete(), patch(), head(), and
options(). Each method is a thin wrapper around the core
request() method, automatically setting the HTTP method and organizing
parameters into a clean, readable function signature. Instead of passing a full options
object with a method property every time, you call the method that matches
the HTTP verb you need and pass only the URL, body (for methods that accept a body),
and any additional options. The convenience methods accept the same options as
request() and return the same standardized response object, so everything
you know about request() applies directly to these methods. This page
provides complete documentation for every HTTP convenience method, including method
signatures, parameter details, practical code examples, comparison with the underlying
request() method, best practices, and common issues.
All seven HTTP convenience methods delegate to request() internally. They
spread your options object, set the url and method properties,
and for post(), put(), and patch(), set the
body property. The response object, error handling, async/sync behavior,
fingerprint merging, cookie handling, and all other features work identically to
request(). Choose the convenience method that matches your HTTP verb for
cleaner, more readable code.
Overview
The HTTP convenience methods fall into two categories based on their parameter
signatures. Methods that typically send a request body (post(),
put(), and patch()) accept three parameters: the URL, the
body content, and an optional options object. Methods that do not typically send a
request body (get(), delete(), head(), and
options()) accept two parameters: the URL and an optional options object.
This distinction keeps the API intuitive and matches the conventions of popular HTTP
client libraries.
Every convenience method returns a Promise that resolves to the same response object
returned by request(). The response includes statusCode,
headers, body, data, cookies,
profile, and processingTime. You can use all the same
response properties and aliases documented on the request() page.
The options parameter on each convenience method accepts every property that
request() accepts except url, method, and
(for body methods) body, because those are set by the convenience method
itself. You can still pass headers, params, mode,
sensibility, fingerprint, proxy,
cookies, timeout, sync,
allowRedirects, maxRedirects, verify,
auth, sessionId, and any other supported option.
Method Signatures
The following table lists all seven HTTP convenience methods with their signatures,
parameter types, and the internal request() call they produce. Each method
spreads the options object first, then sets the url, method,
and optionally body properties. Because the method-specific properties are
set after the spread, they always take precedence over any conflicting values in the
options object.
| Method | Signature | Has Body | Internal Call |
|---|---|---|---|
get() |
client.get(url, options = {}) |
No | request({...options, url, method: "GET"}) |
post() |
client.post(url, body, options = {}) |
Yes | request({...options, url, body, method: "POST"}) |
put() |
client.put(url, body, options = {}) |
Yes | request({...options, url, body, method: "PUT"}) |
delete() |
client.delete(url, options = {}) |
No | request({...options, url, method: "DELETE"}) |
patch() |
client.patch(url, body, options = {}) |
Yes | request({...options, url, body, method: "PATCH"}) |
head() |
client.head(url, options = {}) |
No | request({...options, url, method: "HEAD"}) |
options() |
client.options(url, options = {}) |
No | request({...options, url, method: "OPTIONS"}) |
Parameters Reference
The following tables describe the parameters for both method categories. The first table
covers methods without a body parameter (get, delete,
head, options), and the second table covers methods with a
body parameter (post, put, patch).
Parameters for get(), delete(), head(), options()
| Parameter | Type | Required | Description |
|---|---|---|---|
url |
string | required | The target URL for the HTTP request. Must be a fully qualified URL including the protocol (http or https). |
options |
object | optional | Additional request options. Accepts all properties supported by request() except url and method. Defaults to an empty object. |
Parameters for post(), put(), patch()
| Parameter | Type | Required | Description |
|---|---|---|---|
url |
string | required | The target URL for the HTTP request. Must be a fully qualified URL including the protocol (http or https). |
body |
any | optional | The request body content. Sent as the body property in the underlying request() call. Can be a string, object, Buffer, or any serializable value. |
options |
object | optional | Additional request options. Accepts all properties supported by request() except url, method, and body. Defaults to an empty object. |
client.get(url, options)
The get() method sends an HTTP GET request to the specified URL. GET
requests are used to retrieve data from a server without modifying any resources. This
is the most commonly used HTTP method and is ideal for fetching API data, loading web
pages, downloading files, and querying search endpoints. The method accepts the target
URL as the first parameter and an optional options object as the second parameter. It
internally calls request({...options, url, method: "GET"}).
const BBREClient = require("mydisctsolver-bbre");
const client = new BBREClient({ apiKey: "YOUR_API_KEY" });
const response = await client.get(url, options);
Basic GET Request
The simplest usage of get() requires only the target URL. All other options
use their default values from the client constructor configuration.
const BBREClient = require("mydisctsolver-bbre");
const client = new BBREClient({ apiKey: "YOUR_API_KEY" });
async function fetchProducts() {
const response = await client.get("https://api.example.com/products");
console.log("Status:", response.statusCode);
console.log("Products:", response.data);
console.log("Processing time:", response.processingTime, "ms");
}
fetchProducts();
GET Request with Query Parameters
Pass query parameters through the params property in the options object.
The SDK automatically URL-encodes the values and appends them to the URL as a query
string.
const BBREClient = require("mydisctsolver-bbre");
const client = new BBREClient({ apiKey: "YOUR_API_KEY" });
async function searchProducts() {
const response = await client.get("https://api.example.com/search", {
params: {
query: "wireless headphones",
category: "electronics",
minPrice: 50,
maxPrice: 200,
sort: "price_asc",
page: 1,
limit: 20
}
});
console.log("Status:", response.statusCode);
console.log("Results:", response.data);
}
searchProducts();
GET Request with Custom Headers and Cookies
You can pass custom headers, cookies, and other options through the options object. This example demonstrates fetching a protected resource with authentication headers and session cookies.
const BBREClient = require("mydisctsolver-bbre");
const client = new BBREClient({ apiKey: "YOUR_API_KEY" });
async function fetchProtectedData() {
const response = await client.get("https://api.example.com/user/profile", {
headers: {
"Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9",
"Accept": "application/json",
"Accept-Language": "en-US"
},
cookies: {
session_id: "abc123def456",
csrf_token: "xyz789"
},
timeout: 60
});
console.log("Status:", response.statusCode);
console.log("Profile:", response.data);
}
fetchProtectedData();
GET Request with Adaptive Mode
For websites that require full browser rendering to return content, use adaptive mode. This instructs the BBRE engine to render the page in a real browser before extracting the response.
const BBREClient = require("mydisctsolver-bbre");
const client = new BBREClient({ apiKey: "YOUR_API_KEY" });
async function fetchRenderedPage() {
const response = await client.get("https://spa-app.example.com/dashboard", {
mode: "adaptive",
sensibility: "high",
timeout: 180,
fingerprint: {
platform: "Win32",
timezone: "America/New_York",
language: "en-US"
}
});
console.log("Status:", response.statusCode);
console.log("Page HTML length:", response.body.length);
console.log("Profile used:", response.profile);
}
fetchRenderedPage();
client.post(url, body, options)
The post() method sends an HTTP POST request to the specified URL with a
request body. POST requests are used to submit data to a server, create new resources,
send form data, upload files, and trigger server-side actions. The method accepts the
target URL as the first parameter, the request body as the second parameter, and an
optional options object as the third parameter. It internally calls
request({...options, url, body, method: "POST"}). The body parameter is
sent as the raw body property in the underlying request. If you need
automatic JSON serialization, pass the JSON data through the json property
in the options object instead of the body parameter.
const BBREClient = require("mydisctsolver-bbre");
const client = new BBREClient({ apiKey: "YOUR_API_KEY" });
const response = await client.post(url, body, options);
POST with JSON Body
When sending JSON data, you can pass the object directly as the body parameter. However,
the recommended approach is to use the json property in the options object,
which automatically serializes the data and sets the Content-Type header.
The following example shows both approaches.
const BBREClient = require("mydisctsolver-bbre");
const client = new BBREClient({ apiKey: "YOUR_API_KEY" });
async function createUser() {
const userData = {
name: "Alice Johnson",
email: "[email protected]",
role: "developer"
};
const response = await client.post("https://api.example.com/users", null, {
json: userData
});
console.log("Status:", response.statusCode);
console.log("Created user:", response.data);
}
createUser();
POST with Form Data
For URL-encoded form submissions, pass the form data as a string in the body parameter
and set the appropriate Content-Type header in the options.
const BBREClient = require("mydisctsolver-bbre");
const client = new BBREClient({ apiKey: "YOUR_API_KEY" });
async function submitLoginForm() {
const formData = "username=alice&password=secret123&remember=true";
const response = await client.post("https://shop.example.com/login", formData, {
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
});
console.log("Status:", response.statusCode);
console.log("Cookies:", response.cookies);
}
submitLoginForm();
POST with Raw Body and Custom Headers
You can send any type of body content including XML, plain text, or binary data. Set
the appropriate Content-Type header to match your body format.
const BBREClient = require("mydisctsolver-bbre");
const client = new BBREClient({ apiKey: "YOUR_API_KEY" });
async function sendXmlData() {
const xmlBody = '<order><item id="123"><quantity>2</quantity></item></order>';
const response = await client.post("https://api.example.com/orders", xmlBody, {
headers: {
"Content-Type": "application/xml",
"Accept": "application/xml"
},
timeout: 90
});
console.log("Status:", response.statusCode);
console.log("Response:", response.body);
}
sendXmlData();
POST with Proxy and Fingerprint
Combine the POST method with proxy routing and fingerprint configuration for requests that need to appear from a specific geographic location with a specific browser identity.
const BBREClient = require("mydisctsolver-bbre");
const client = new BBREClient({ apiKey: "YOUR_API_KEY" });
async function submitWithProxy() {
const response = await client.post(
"https://geo-service.example.com/register",
null,
{
json: {
name: "Alice Johnson",
country: "DE",
language: "de"
},
proxy: {
host: "proxy.example.com",
port: 8080,
username: "proxyuser",
password: "proxypass"
},
fingerprint: {
platform: "Win32",
timezone: "Europe/Berlin",
language: "de-DE"
},
mode: "passive",
sensibility: "medium"
}
);
console.log("Status:", response.statusCode);
console.log("Registration result:", response.data);
}
submitWithProxy();
client.put(url, body, options)
The put() method sends an HTTP PUT request to the specified URL with a
request body. PUT requests are used to replace an existing resource entirely with the
provided data. Unlike PATCH, which applies partial modifications, PUT replaces the
entire resource representation. The method accepts the target URL as the first parameter,
the request body as the second parameter, and an optional options object as the third
parameter. It internally calls
request({...options, url, body, method: "PUT"}). Use PUT when you want to
update a resource by sending its complete new representation to the server.
const BBREClient = require("mydisctsolver-bbre");
const client = new BBREClient({ apiKey: "YOUR_API_KEY" });
const response = await client.put(url, body, options);
Replace a Resource with PUT
The following example replaces an entire user profile with new data. The server expects the complete resource representation in the request body.
const BBREClient = require("mydisctsolver-bbre");
const client = new BBREClient({ apiKey: "YOUR_API_KEY" });
async function updateUserProfile() {
const updatedProfile = {
name: "Alice Johnson",
email: "[email protected]",
role: "senior-developer",
department: "Engineering",
preferences: {
theme: "dark",
notifications: true,
language: "en-US"
}
};
const response = await client.put(
"https://api.example.com/users/12345",
null,
{ json: updatedProfile }
);
console.log("Status:", response.statusCode);
console.log("Updated user:", response.data);
}
updateUserProfile();
PUT with Authentication
When updating protected resources, include authentication credentials through headers
or the auth option in the options object.
const BBREClient = require("mydisctsolver-bbre");
const client = new BBREClient({ apiKey: "YOUR_API_KEY" });
async function updateSettings() {
const newSettings = {
notifications: { email: true, sms: false, push: true },
privacy: { profileVisible: false, searchable: true },
timezone: "Europe/London"
};
const response = await client.put(
"https://api.example.com/users/12345/settings",
null,
{
json: newSettings,
headers: {
"Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9"
}
}
);
console.log("Status:", response.statusCode);
console.log("Settings updated:", response.data);
}
updateSettings();
PUT with Sync Mode
For update operations where you need immediate confirmation, use synchronous execution mode to eliminate polling overhead and get the response in a single round trip.
const BBREClient = require("mydisctsolver-bbre");
const client = new BBREClient({ apiKey: "YOUR_API_KEY" });
async function syncUpdate() {
const productData = {
name: "Wireless Headphones Pro",
price: 149.99,
stock: 250,
category: "electronics",
description: "Premium wireless headphones with noise cancellation"
};
const response = await client.put(
"https://api.example.com/products/789",
null,
{
json: productData,
sync: true,
timeout: 60
}
);
console.log("Status:", response.statusCode);
console.log("Product updated:", response.data);
}
syncUpdate();
client.delete(url, options)
The delete() method sends an HTTP DELETE request to the specified URL.
DELETE requests are used to remove a resource from the server. The method accepts the
target URL as the first parameter and an optional options object as the second parameter.
It internally calls request({...options, url, method: "DELETE"}). Unlike
post(), put(), and patch(), the
delete() method does not accept a body parameter in its signature. If you
need to send a body with a DELETE request (which some APIs require), pass it through the
body or json property in the options object.
const BBREClient = require("mydisctsolver-bbre");
const client = new BBREClient({ apiKey: "YOUR_API_KEY" });
const response = await client.delete(url, options);
Delete a Resource
The simplest DELETE request targets a specific resource by its URL. Most REST APIs identify the resource to delete through the URL path.
const BBREClient = require("mydisctsolver-bbre");
const client = new BBREClient({ apiKey: "YOUR_API_KEY" });
async function deleteUser() {
const response = await client.delete("https://api.example.com/users/12345");
console.log("Status:", response.statusCode);
console.log("Deleted:", response.data);
}
deleteUser();
Delete with Authentication Headers
Delete operations on protected resources require authentication. Pass the authorization token through the headers option.
const BBREClient = require("mydisctsolver-bbre");
const client = new BBREClient({ apiKey: "YOUR_API_KEY" });
async function deleteWithAuth() {
const response = await client.delete("https://api.example.com/posts/67890", {
headers: {
"Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9"
}
});
if (response.statusCode === 204) {
console.log("Post deleted successfully");
} else {
console.log("Unexpected status:", response.statusCode);
console.log("Response:", response.data);
}
}
deleteWithAuth();
Delete with Body in Options
Some APIs require a request body with DELETE requests to specify additional deletion
parameters. Since the delete() method signature does not include a body
parameter, pass the body through the json property in the options object.
const BBREClient = require("mydisctsolver-bbre");
const client = new BBREClient({ apiKey: "YOUR_API_KEY" });
async function bulkDelete() {
const response = await client.delete("https://api.example.com/items", {
json: {
ids: [101, 102, 103, 104, 105],
reason: "cleanup",
permanent: false
},
headers: {
"Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9"
}
});
console.log("Status:", response.statusCode);
console.log("Deleted count:", response.data.deletedCount);
}
bulkDelete();
client.patch(url, body, options)
The patch() method sends an HTTP PATCH request to the specified URL with a
request body. PATCH requests are used to apply partial modifications to an existing
resource. Unlike PUT, which replaces the entire resource, PATCH sends only the fields
that need to be changed. The method accepts the target URL as the first parameter, the
request body as the second parameter, and an optional options object as the third
parameter. It internally calls
request({...options, url, body, method: "PATCH"}). Use PATCH when you want
to update specific fields of a resource without sending the complete representation.
const BBREClient = require("mydisctsolver-bbre");
const client = new BBREClient({ apiKey: "YOUR_API_KEY" });
const response = await client.patch(url, body, options);
Partial Update with PATCH
The following example updates only the email and role fields of a user profile. All other fields remain unchanged on the server.
const BBREClient = require("mydisctsolver-bbre");
const client = new BBREClient({ apiKey: "YOUR_API_KEY" });
async function updateUserEmail() {
const response = await client.patch(
"https://api.example.com/users/12345",
null,
{
json: {
email: "[email protected]",
role: "lead-developer"
}
}
);
console.log("Status:", response.statusCode);
console.log("Updated fields:", response.data);
}
updateUserEmail();
PATCH with Nested Object Updates
PATCH is particularly useful when updating nested properties within a resource. You can send only the nested fields that changed without affecting sibling properties.
const BBREClient = require("mydisctsolver-bbre");
const client = new BBREClient({ apiKey: "YOUR_API_KEY" });
async function updateNotificationPreferences() {
const response = await client.patch(
"https://api.example.com/users/12345/preferences",
null,
{
json: {
notifications: {
email: false,
push: true
}
},
headers: {
"Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9"
}
}
);
console.log("Status:", response.statusCode);
console.log("Updated preferences:", response.data);
}
updateNotificationPreferences();
PATCH with Error Handling
Always wrap PATCH requests in error handling to catch validation errors, authorization failures, and resource not found responses from the target server.
const BBREClient = require("mydisctsolver-bbre");
const client = new BBREClient({ apiKey: "YOUR_API_KEY" });
async function safePatchUpdate() {
try {
const response = await client.patch(
"https://api.example.com/products/789",
null,
{
json: { price: 129.99, stock: 500 },
timeout: 60
}
);
if (response.statusCode === 200) {
console.log("Product updated:", response.data);
} else if (response.statusCode === 404) {
console.log("Product not found");
} else if (response.statusCode === 422) {
console.log("Validation error:", response.data);
}
} catch (error) {
console.log("Request failed:", error.message);
}
}
safePatchUpdate();
client.head(url, options)
The head() method sends an HTTP HEAD request to the specified URL. HEAD
requests are identical to GET requests except that the server does not return a response
body. The server returns only the response headers, which include metadata such as
content type, content length, last modified date, caching directives, and server
information. HEAD requests are useful for checking whether a resource exists, verifying
content type before downloading, checking file sizes, and validating cache freshness
without transferring the full response body. The method accepts the target URL as the
first parameter and an optional options object as the second parameter. It internally
calls request({...options, url, method: "HEAD"}).
const BBREClient = require("mydisctsolver-bbre");
const client = new BBREClient({ apiKey: "YOUR_API_KEY" });
const response = await client.head(url, options);
Check Resource Existence
Use HEAD to verify that a URL is accessible and returns a successful status code without downloading the full response body. This is efficient for link validation and health checks.
const BBREClient = require("mydisctsolver-bbre");
const client = new BBREClient({ apiKey: "YOUR_API_KEY" });
async function checkResourceExists() {
const response = await client.head("https://cdn.example.com/files/report.pdf");
if (response.statusCode === 200) {
console.log("Resource exists");
console.log("Content-Type:", response.headers["content-type"]);
console.log("Content-Length:", response.headers["content-length"]);
console.log("Last-Modified:", response.headers["last-modified"]);
} else if (response.statusCode === 404) {
console.log("Resource not found");
}
}
checkResourceExists();
Check File Size Before Download
Before downloading a large file, use HEAD to check the file size through the
Content-Length header. This allows you to make informed decisions about
whether to proceed with the download based on available storage or bandwidth.
const BBREClient = require("mydisctsolver-bbre");
const client = new BBREClient({ apiKey: "YOUR_API_KEY" });
async function checkFileSize() {
const fileUrl = "https://cdn.example.com/downloads/dataset.zip";
const headResponse = await client.head(fileUrl);
const contentLength = parseInt(headResponse.headers["content-length"], 10);
const fileSizeMB = (contentLength / (1024 * 1024)).toFixed(2);
console.log("File size:", fileSizeMB, "MB");
console.log("Content-Type:", headResponse.headers["content-type"]);
const maxSizeMB = 100;
if (parseFloat(fileSizeMB) <= maxSizeMB) {
console.log("File size is within limit, proceeding with download");
const downloadResponse = await client.get(fileUrl);
console.log("Download status:", downloadResponse.statusCode);
} else {
console.log("File exceeds size limit of", maxSizeMB, "MB");
}
}
checkFileSize();
Validate Cache Freshness
Use HEAD with conditional headers to check whether a cached resource is still fresh without downloading the full content. The server responds with 304 Not Modified if the resource has not changed.
const BBREClient = require("mydisctsolver-bbre");
const client = new BBREClient({ apiKey: "YOUR_API_KEY" });
async function validateCache() {
const cachedETag = '"abc123def456"';
const cachedLastModified = "Wed, 15 Jan 2025 10:30:00 GMT";
const response = await client.head("https://api.example.com/data/catalog", {
headers: {
"If-None-Match": cachedETag,
"If-Modified-Since": cachedLastModified
}
});
if (response.statusCode === 304) {
console.log("Cache is still fresh, no download needed");
} else if (response.statusCode === 200) {
console.log("Resource has been updated, cache needs refresh");
console.log("New ETag:", response.headers["etag"]);
console.log("New Last-Modified:", response.headers["last-modified"]);
}
}
validateCache();
client.options(url, options)
The options() method sends an HTTP OPTIONS request to the specified URL.
OPTIONS requests are used to discover the communication options available for a target
resource. The server responds with headers that describe the allowed HTTP methods,
supported content types, and CORS (Cross-Origin Resource Sharing) configuration. This
method is primarily used for CORS preflight checks, API capability discovery, and
debugging server configuration. The method accepts the target URL as the first parameter
and an optional options object as the second parameter. It internally calls
request({...options, url, method: "OPTIONS"}).
const BBREClient = require("mydisctsolver-bbre");
const client = new BBREClient({ apiKey: "YOUR_API_KEY" });
const response = await client.options(url, options);
Discover Allowed Methods
Use OPTIONS to discover which HTTP methods a server endpoint supports. The server
returns the allowed methods in the Allow header.
const BBREClient = require("mydisctsolver-bbre");
const client = new BBREClient({ apiKey: "YOUR_API_KEY" });
async function discoverAllowedMethods() {
const response = await client.options("https://api.example.com/users");
console.log("Status:", response.statusCode);
console.log("Allowed methods:", response.headers["allow"]);
console.log("Content-Type options:", response.headers["accept"]);
}
discoverAllowedMethods();
CORS Preflight Check
Simulate a CORS preflight request by sending an OPTIONS request with the appropriate CORS headers. This is useful for debugging cross-origin issues and verifying that a server is configured to accept requests from specific origins.
const BBREClient = require("mydisctsolver-bbre");
const client = new BBREClient({ apiKey: "YOUR_API_KEY" });
async function corsPreflightCheck() {
const response = await client.options("https://api.example.com/data", {
headers: {
"Origin": "https://myapp.example.com",
"Access-Control-Request-Method": "POST",
"Access-Control-Request-Headers": "Content-Type, Authorization"
}
});
console.log("Status:", response.statusCode);
console.log("Allowed Origin:", response.headers["access-control-allow-origin"]);
console.log("Allowed Methods:", response.headers["access-control-allow-methods"]);
console.log("Allowed Headers:", response.headers["access-control-allow-headers"]);
console.log("Max Age:", response.headers["access-control-max-age"]);
}
corsPreflightCheck();
API Capability Discovery
Some APIs use OPTIONS responses to communicate additional capabilities, supported versions, or rate limit information. Use OPTIONS to inspect these details before making actual data requests.
const BBREClient = require("mydisctsolver-bbre");
const client = new BBREClient({ apiKey: "YOUR_API_KEY" });
async function discoverApiCapabilities() {
const response = await client.options("https://api.example.com/v2/resources");
console.log("Status:", response.statusCode);
console.log("Allow:", response.headers["allow"]);
console.log("API Version:", response.headers["x-api-version"]);
console.log("Rate Limit:", response.headers["x-rate-limit-limit"]);
console.log("Rate Remaining:", response.headers["x-rate-limit-remaining"]);
const allowedMethods = (response.headers["allow"] || "").split(",").map(m => m.trim());
console.log("Supported methods:", allowedMethods);
}
discoverApiCapabilities();
Comparison with request() Method
The HTTP convenience methods and the request() method produce identical
results. The convenience methods exist purely for developer ergonomics. They reduce
boilerplate by eliminating the need to specify the method property in the
options object and by promoting the URL and body to dedicated function parameters. The
following examples show the same operations written with both approaches so you can see
the difference in readability and code structure.
GET Comparison
A simple GET request written with request() versus get(). The
convenience method eliminates the options object wrapper for simple requests.
const BBREClient = require("mydisctsolver-bbre");
const client = new BBREClient({ apiKey: "YOUR_API_KEY" });
async function getComparison() {
const responseA = await client.request({
url: "https://api.example.com/products",
method: "GET",
params: { category: "electronics", limit: 10 }
});
const responseB = await client.get("https://api.example.com/products", {
params: { category: "electronics", limit: 10 }
});
}
getComparison();
POST Comparison
A POST request with a JSON body written with request() versus
post(). The convenience method separates the URL and body from the options,
making the intent clearer.
const BBREClient = require("mydisctsolver-bbre");
const client = new BBREClient({ apiKey: "YOUR_API_KEY" });
async function postComparison() {
const userData = { name: "Alice", email: "[email protected]" };
const responseA = await client.request({
url: "https://api.example.com/users",
method: "POST",
json: userData
});
const responseB = await client.post("https://api.example.com/users", null, {
json: userData
});
}
postComparison();
DELETE Comparison
A DELETE request with authentication written with request() versus
delete().
const BBREClient = require("mydisctsolver-bbre");
const client = new BBREClient({ apiKey: "YOUR_API_KEY" });
async function deleteComparison() {
const responseA = await client.request({
url: "https://api.example.com/users/12345",
method: "DELETE",
headers: { "Authorization": "Bearer token123" }
});
const responseB = await client.delete("https://api.example.com/users/12345", {
headers: { "Authorization": "Bearer token123" }
});
}
deleteComparison();
When to Use request() Directly
While the convenience methods cover the vast majority of use cases, there are scenarios
where calling request() directly is preferable. Use request()
when you need to dynamically determine the HTTP method at runtime, when building generic
HTTP client wrappers, or when the method name is stored in a variable or configuration
object.
const BBREClient = require("mydisctsolver-bbre");
const client = new BBREClient({ apiKey: "YOUR_API_KEY" });
async function dynamicRequest(method, url, body) {
const options = { url, method: method.toUpperCase() };
if (body) {
options.json = body;
}
const response = await client.request(options);
return response;
}
async function runDynamicRequests() {
const getResult = await dynamicRequest("GET", "https://api.example.com/users");
console.log("GET status:", getResult.statusCode);
const postResult = await dynamicRequest("POST", "https://api.example.com/users", {
name: "Alice",
email: "[email protected]"
});
console.log("POST status:", postResult.statusCode);
}
runDynamicRequests();
Feature Comparison Table
The following table summarizes the differences between using convenience methods and
the request() method directly.
| Feature | Convenience Methods | request() Method |
|---|---|---|
| URL parameter | First function argument | Property in options object |
| HTTP method | Determined by function name | Property in options object |
| Body parameter | Second argument (post, put, patch only) | Property in options object |
| Additional options | Last function argument | Same options object as url and method |
| Dynamic method selection | Requires conditional logic to choose method | Method name as a string variable |
| Response object | Identical to request() | Standard response object |
| Error handling | Identical to request() | Standard error handling |
| Async/Sync support | Identical to request() | Full async and sync support |
Best Practices
Prefer the convenience methods (get(), post(),
put(), delete(), patch()) over
request() for standard HTTP operations. The convenience methods make
the HTTP verb immediately visible in the function name, improving code readability
and making it easier for other developers to understand the intent of each request
at a glance. Reserve request() for dynamic method selection or generic
wrapper functions.
When sending JSON data with post(), put(), or
patch(), pass the data through the json property in the
options object rather than serializing it manually and passing it as the body
parameter. The json option automatically handles
JSON.stringify() serialization and sets the
Content-Type: application/json header, eliminating common mistakes
like forgetting the Content-Type header or double-serializing the data.
When updating specific fields of a resource, use patch() instead of
put(). PATCH sends only the changed fields, reducing the request
payload size and avoiding the risk of accidentally overwriting fields that you did
not intend to change. Use put() only when you need to replace the
entire resource representation with a new version.
Before downloading large files or making expensive GET requests, use
head() to check the resource metadata. The HEAD response includes
headers like Content-Length, Content-Type, and
Last-Modified without transferring the response body. This saves
bandwidth and processing time when you only need to verify resource existence,
check file sizes, or validate cache freshness.
Every HTTP convenience method can throw errors due to network failures, timeouts,
insufficient balance, or invalid parameters. Wrap all method calls in try-catch
blocks and implement appropriate error handling for each error type. Check the
response.statusCode to handle target server errors separately from
BBRE engine errors. Implement retry logic with exponential backoff for transient
errors like SERVICE_UNAVAILABLE and SERVICE_TIMEOUT.
A successful BBRE request (where the Promise resolves without throwing) means the
BBRE engine received a response from the target server. However, the target server
may have returned a 4xx or 5xx status code. Always check
response.statusCode before processing response.data or
response.body to ensure the target server returned the expected
successful response.
When you need to maintain state across multiple requests (such as login followed by
data retrieval), use BBRE sessions with the sessionId option instead
of manually forwarding cookies between convenience method calls. Sessions
automatically manage cookies, browser state, and profile consistency, providing a
more reliable approach to stateful workflows than manual cookie management.
Common Issues
Symptom: You pass a body as the second argument to
get(), delete(), head(), or
options(), but the target server does not receive any body content.
Cause: These four methods accept only two parameters:
(url, options). The second argument is treated as the options object,
not as a body. If you pass a string or object as the second argument, it is
interpreted as request options, not as body content.
Solution: For methods without a body parameter, pass body content
through the body or json property inside the options
object. For example:
client.delete(url, { json: { ids: [1, 2, 3] } }).
Symptom: The target server returns a 400 Bad Request or does not
parse the JSON body when using post(), put(), or
patch() with a JavaScript object as the body parameter.
Cause: The body parameter is sent as-is through the
body property of request(). It does not automatically
serialize objects to JSON or set the Content-Type header.
Solution: Use the json property in the options object
instead of the body parameter for JSON data. Pass null as the body
parameter and include your data in options.json. For example:
client.post(url, null, { json: myData }).
Symptom: You set method, url, or
body in the options object, but the values you set are ignored.
Cause: The convenience methods spread the options object first,
then set url, method, and body after the
spread. This means the method-specific values always override any matching
properties in the options object. For example,
client.get(url, { method: "POST" }) still sends a GET request because
the method: "GET" is set after the spread.
Solution: Do not set url, method, or
body in the options object when using convenience methods. These
properties are controlled by the method signature. If you need to override the
method, use request() directly.
Symptom: The response.body and
response.data are empty or undefined after a head()
request, even though the same URL returns content with get().
Cause: This is expected behavior. The HTTP HEAD method instructs
the server to return only response headers without a body. The response headers
contain metadata about the resource (content type, content length, last modified
date) but the actual content is not transferred.
Solution: Access the information you need from
response.headers instead of response.body. If you need
the actual content, use get() instead of head().
Symptom: Requests using convenience methods with
mode: "adaptive" and sensibility: "high" consistently
fail with timeout errors.
Cause: Adaptive mode with high sensibility requires the BBRE engine
to perform full browser rendering with additional evasion steps, which can take
significantly longer than passive mode requests. The default timeout may be
insufficient for complex pages.
Solution: Increase the timeout value in the options
object to 180 or 240 seconds for adaptive mode requests with high sensibility. You
can also set a higher default timeout in the client constructor for all requests.