Send HTTP Requests To a Server with Node.js

It’s actually incredibly easy to send http/https requests to servers with Node.js. Node contains a bunch of native function for that, making it very easy to send REST requests. I’m going to demonstrate with Node’s own http.request(options[, callback]) method.

http-between-servers

HTTP/HTTPS requests in a very brief glance

The four most common HTTP requests are GET, POST, PUT, DELETE. The type of request determines the type of operation the request sender would like the server to perform.

If you’re sending REST API requests to a server, the documentation will(should) point you to exactly what the request is and how a sample request looks like.

GET is just the URL with or without headers. There are some common headers, like authorization. Without the headers it’s just like typing an address in your server. A GET request doesn’t change anything on the requested server.

An example GET request looks like this:

GET /viewingservice/v1/supported HTTP/1.1
Host: developer.api.autodesk.com
Authorization: Bearer OM0GTVs3ycQ0nkU9X9cneBnInOuE

POST is a request with headers and/or data. Data can usually be a string or a data stream, which means it’s a file.

An example POST request looks like this:

POST /authentication/v1/authenticate HTTP/1.1
Host: developer.api.autodesk.com
Content-Type: application/x-www-form-urlencoded
client_id=my_client_id&client_secret=my_client_secret&grant_type=client_credentials

PUT is similar to POST but idempotent, which means no matter how many times you send the request the result will be the same.

An example PUT request looks like this:

PUT /oss/v1/buckets/shiyas-bucket-100/objects/sometext.txt HTTP/1.1
Host: developer.api.autodesk.com
Authorization: Bearer OM0GTVs3ycQ0nkU9X9cneBnInOuE
Content-Type: application/octet-stream
"some text string"

Notice how the URI on the first line points to the exact location of the resource. No matter how many times I send the request, I will only have one resource that contains "some text string" with the URI /oss/v1/buckets/shiyas-bucket-100/objects/sometext.txt.

DELETE is what it sounds like, deleting a resource from the requested server. You need to know the exact URL of the resource you’d like to delete.

An example DELETE request looks like this:

DELETE /derivativeservice/v2/registration/{{resource_urn}} HTTP/1.1
Host: developer.api.autodesk.com
Authorization: Bearer glKJvrua6pWF5ogsOg9f3oOs69SC

It really is up to the discretion of who designs the API exactly what these request will do on their server.

Now we’ve understood what the requests do, it’s time to implement in Node.js.

http.request(options[, callback])

Node’s https is just http over TLS/SSL, the syntax are the same. When writing a https request, just replace http with https.

First include the http module:

var http = require("http");

Then create a variable called options, this is going to contain all the parameters in the request.

A POST request example:

var options = {
	host: "developer.api.autodesk.com",
	path: "/oss/v1/buckets",
	method: "POST",
	headers: {
		"Content-Type": "application/json"
		"Authorization": "Bearer token"
	}
};

A PUT request example:

var bucket = {};
bucket.name = "shiyas-bucket";

var file = {};
file.name = "sometext.txt";

var options = {
	host: "developer.api.autodesk.com",
	path: "/oss/v1/buckets/" + bucket.name + "/objects/" + file.name,
	method: "PUT", 
	headers: {
		"Content-Type": "application/octet-stream",
		"Authorization": "Bearer token"
	}
};

Notice how the path in the POST request is a general path while PUT request points to the exact location of the resource.

Now construct the request with options and a callback function.

The callback function occurs after you’ve sent the request, so it does things to the response, when you get one. In the callback function, write listeners that defines what you’d like to do when you get a response.

var req = http.request(options, function (res) {
	var responseString = "";

	res.on("data", function (data) {
		responseString += data;
		// save all the data from response
	});
	res.on("end", function () {
		console.log(responseString); 
		// print to console when response ends
	});
});

Sending the request:

req.write();

If there’s a request body, like in a POST or PUT request, pass in the request body.

var reqBody = "sometext";
req.write(reqBody);

reqBody here is a string, it can also be a buffer. Use a module like fs to handle file streams.

Lastly, end the request:

req.end();

That’s it!

Read Node’s documentation on http.request for more details.

Refer to one of my examples for complete working code.

Leave a Reply

Your email address will not be published. Required fields are marked *