HTTP Request Methods and How They are Written

Randolph Perkins
8 min readFeb 22, 2021

The core technology of the World Wide Web is HTTPHypertext Transfer Protocol. It’s the communication protocol that is used any time one browses the web. At a fundamental level, when you visit a website, your browser makes an HTTP request to a server. Then that server responds with a resource (an image, video, or the HTML of a web page) — which your browser then displays for you. This is HTTP’s message-based model and every HTTP interaction includes a request and a response. Because this layer of operations is so essential to how data is transferred between mediums, I would like to examine the usage and common examples of HTTP request methods, and how they may be implemented from the perspective of full-stack web development. Also known as HTTP verbs, these methods indicate the desired action to be performed for a given resource. It would be useful to first touch on some of the other features of HTTP operations; then I aim to introduce the most commonly used request methods, and finally give actual code examples of implementation, using a few different libraries, frameworks and approaches. Let’s go!

HTTP Origins + The Client/Server Model

HTTP is known as a request-response protocol in the client/server computing model. In this relationship a web browser may be thought of as the client, whereas the application running which hosts the website would be the server. The client in this case submits an HTTP request message to the server, and the server provides resources (HTML, JavaScript, et al), performs functions for the client, and then returns a response message, containing status information and possibly requesting more content therein.

HTTP is known as a stateless protocol, in that it does not need to retain information about individual clients while undergoing multiple requests. Yet some web apps create states on their own using hidden variables or HTTP cookies. HTTP/1.1 is a revision of the original protocol (HTTP/1.0) and a major advantage of /1.1 is its reuse of connections after the web page has been delivered, in the form of images, scripts, and CSS or related stylesheets. This creates significantly less latency, an area that will be further improved upon in future versions.

Computer scientist Tim Berners-Lee and his team at CERN (European Organization for Nuclear Research) are credited with creating the original protocol and related technology such as HTML, while first proposing a model for the World Wide Web in 1989. In its earliest incarnation, HTTP only used one method, “GET”, which made a request to a server, and the server’s response would be in HTML form.

Before We Dive In…

Let’s define some key terminology as applied to HTTP and its operations. The URL (Uniform Resource Locator) is probably the most known concept of the Web. A URL is a web address used to identify resources on the Web. The idea of the web is structured around resources. From its beginnings the Web was the platform for sharing text/HTML files, documents, images etc, and as such it can be considered a collection of resources.

(You have seen this before.)

Protocol — Most often they are HTTP (or HTTPS for a secure version of HTTP). Other notable protocols are:

  • File Transfer Protocol (FTP) — a standard protocol used for transferring files between a client and a server over a network.
  • Simple Mail Transfer Protocol (SMTP) — standard for email transmission.

Domain — Name that is used to identify one or more IP addresses where the resource is located.

Path — Specifies the resource location on the server. It uses the same logic as a resource location used on the device where you are reading this very article.

Parameters — Additional data used to identify or filter the resource on the server.

HTTP Request Methods

To begin with, in HTTP, every request must have an URL address. Additionally, the request needs a method. Each method implements a specific semantic, but there are some common features shared by a group of them. For example, a request method can be safe, idempotent, or cacheable. We will get into those features shortly. For now, let’s look at the main HTTP request methods, or verbs:

  • GET — This method requests representations of the resource specified in the resource we are interacting with. A GET request only retrieves data, and doesn’t change the state of the resource.
  • POST — This is the request method used in order to send data to a resource, in essence creating a new resource. Using POST has the potential to actually cause a change in a resource’s state, and also can generate side effects on the server.
  • PUT — To replace current representations of the target resource with the request’s data, this method is used. It may be thought of as a method which updates or edits something.
  • DELETE — As can be expected, this HTTP verb is used for deleting a specified resource.

These four request methods are the most frequently used in carrying out file transfer operations for this protocol, and correspond to the four basic functions of persistent storage, known as CRUD (create, read, update, delete). Here are a few more:

  • PATCH — Used for applying partial modifications, PATCH may be considered as a set of instructions for how a resource is to be modified.
  • HEAD — The HEAD method requests the headers which would be returned from using a typical GET request. An example of this is when the user would like to check the file size of a large download, without downloading it.
  • TRACE — A method used simply for diagnostic purposes, for testing the path to the target resource.
  • OPTIONS — For describing communication options for the target resource.

A Few More Descriptions

A request method is considered safe when it doesn’t alter the server, i.e. if it is a read-only operation. GET, HEAD, and OPTIONS are all safe in this respect. Additionally, certain methods may be idempotent, which means that they cause the same effect when used multiple times, and do not have side effects. This feature is similar to the ‘pure’ designation given to functions written in JavaScript. Request methods can also be cacheable, meaning that their responses can be stored to be retrieved at a later time.

In order for HTTP requests to be valid, they must have at least one header, an optional body, the request method, a requested URL, and the version of HTTP must be specified. Responses will always contain the HTTP version, the numeric code of the request’s result, and then a text description of the numeric code. Depending on the request method used, a response may also contain a message body.

Now that we have covered a majority of the constituents of HTTP requests, along with identifying the essential methods or verbs which are used, we can move on to actual code examples of this process, all using JavaScript as the core programming language.

Putting It All Together

There are a few ways to make HTTP requests. They can be made using native functions in JavaScript. However, certain dependencies, such as frameworks and libraries, as well as web APIs, provide methods for making requests, often in more streamlined and simpler ways. We will look at a few of these approaches in detail.

Native JavaScript — Ajax

AJAX simply stands for Asynchronous JavaScript And Xml. It makes use of an XMLHttpRequest object for communicating with web servers, which is able to send and receive data in a few common formats: JSON, XML, HTML, or simple text. The most salient aspect of AJAX is its asynchronous nature, which means that requests to the server are able to be made without a page reload. Here is an example AJAX request:

const Http = new XMLHttpRequest();
const url='https://jsonplaceholder.typicode.com/posts';
Http.open("GET", url);
Http.send();

Http.onreadystatechange = (e) => {
console.log(Http.responseText)
}

The code above makes a new XMLHttpRequest object, and uses a URL which returns random data in JSON format. Notice we used a GET request method, meaning we are just retrieving data, and not making a change to the resource. If used in the browser’s dev tools, the response text will be logged to the console.

Using jQuery For HTTP Requests

The jQuery JavaScript library is immensely popular due to its ability to simplify many common JavaScript operations, and making server requests is no exception. The library contains a few HTTP request methods, all of which use the $ syntax. This includes the $.ajax method, as shown here:

$(document).ready(function(){
const Url='https://jsonplaceholder.typicode.com/posts';
$('.btn').click(function() {
$.ajax({
url: Url,
type: "GET",
success: function(result) {
console.log(result)
},
error: function(error) {
console.log('Error ${error}')
}
})
})
})

In the above implementation, the $.ajax method takes a few parameters, including ‘type’, which is where the particular request method is specified, and ‘success/error’, parameters which use passed in functions to be called depending on whether the request made to the server was successful or not. In addition, jQuery has specific $.get and $.post methods, as well as a $.getJSON method, which will only retrieve data that is in JSON format.

Axios: Promise-Based Requests

There is also an open source JavaScript library for making HTTP requests called Axios. It can be installed on the command line using node package manager (npm), or simply added as a script to a project’s HTML file. A major benefit of Axios is that it returns a promise, a condition which allows for multiple requests to be made at once. The following is an example of using two GET requests at once, with the axios.all method:

function getUser() {
const userUrl='https://jsonplaceholder.typicode.com/users';
return axios.get(userUrl)
}
function getPost() {
const postUrl='https://jsonplaceholder.typicode.com/posts';
return axios.get(postUrl)
}
axios.all([getUser().getPost()])
.then((users.posts)=>{
console.log(users)
console.log(posts)
})
.catch(err=>console.log(err))

I hope this blog entry has presented a decent introduction to the HTTP protocol, and that it has served you well! Thank you for reading.

Sources:

--

--