Http- Hypertext Transfer Protocol

Neha SawantNeha Sawant
6 min read

Why the HTTP Protocol?

HTTP (Hypertext Transfer Protocol) is the foundation of data communication on the web. It allows clients (like browsers, Postman, or mobile apps) to communicate with servers.

Try exploring the network tab and seeing all the HTTP requests that go out when you visit https://google.com

Request Response model:

The request-response model is a fundamental communication pattern.

It describes how data is exchanged between a client and a server or between two systems.

Are there other ways for you to communicate b/w machines?

Yes, there are various other protocols that exist that let machines communicate with each other.

  1. Websockets

  2. WebRTC

  3. GRPC

Domain name/IP

Domain names

The way to reach a sever is through its Domain name . For example

  1. google.com

  2. app.100xdevs.com

  3. x.com

IPs

Every domain that you see, actually has an underlying IP that it resolves to.

You can check the ip by running the ping command.

Ports

In networking, ports are logical endpoints used by protocols to identify specific processes running on a computer or server. They help direct network traffic to the correct application or service on a system.

Methods

HTTP methods are used to specify the type of action that the client wants to perform on a resource on the server.

Common methods

  1. GET - Retrieve data from a server. (Get my TODOS)

  2. POST - Submit data to be processed by a server. (Create a TODO)

  3. PUT - Update or create a resource on the server (Update my todo)

  4. DELETE - Remove a resource from the server. (Delete my todo)

Response

The response represents what the server returns you in response to the request.

It could be

  1. Plaintext data - Not used as often

  2. HTML - If it is a website

  3. JSON Data - If you want to fetch some data (user details, list of todos…)

JSON

JSON stands for JavaScript Object Notation. It is a lightweight, text-based format used for data interchange.

Status codes

HTTP status codes are three-digit numbers returned by a server to indicate the outcome of a client’s request. They provide information about the status of the request and the server's response.

200 series (Success)

  • 200 OK: The request was successful, and the server returned the requested resource.

  • 204 No Content: The request was successful, but there is no content to send in the response

300 series (Redirection)

  • 301 Moved Permanently: The requested resource has been moved to a new URL permanently. The client should use the new URL provided in the response.

  • 304 Not Modified: The resource has not been modified since the last request. The client can use the cached version.

400 series (Client Error)

  • 400 Bad Request: The server could not understand the request due to invalid syntax.

  • 401 Unauthorized: The request requires user authentication. The client must provide credentials.

  • 403 Forbidden: The server understood the request but refuses to authorize it.

  • 404 Not Found: The requested resource could not be found on the server.

500 series (Server Error)

  • 500 Internal Server Error: The server encountered an unexpected condition that prevented it from fulfilling the request.

  • 502 Bad Gateway: The server received an invalid response from an upstream server while acting as a gateway or proxy.

Body

In HTTP communications, the body (or payload) refers to the part of an HTTP message that contains the actual data being sent to the server.

It is usually JSON data that is transferred to the server.

For example -

Routes

In the context of HTTP, routes are paths or endpoints that define how incoming requests are handled by a server. Routing is a mechanism used to direct incoming HTTP requests to the appropriate handler functions or resources based on the URL path.

Headers

HTTP headers are key-value pairs included in HTTP requests and responses that provide metadata about the message.

HTTP headers are key-value pairs sent between a client (like a web browser) and a server in an HTTP request or response. They convey metadata about the request or response, such as content type, auth information etc.

Common headers

  1. Authorization (Sends the user auth information)

  2. Content-Type - Type of information client is sending (json, binary etc)

  3. Referer - Which URL is this request coming from

The headers the client sends out in the request are known as request headers

notion image

Response headers

The headers that the server responds with are known as the response headers.

notion image

Why not use body?

Even though you can use body for everything, it is a good idea to use headers for sending data that isn’t directly related with the application logic.

For example, if you want to create a new TODO, you will send the TODO payload in the body

But the Authorization information in the headers

Clients (Postman/curl/browser):

Postman lets you send HTTP requests to a server, just like your browser. It gives you a prettier interface to send requests and play with them.

You can send a request from various clients , Postman being one of them.

Installing postman - https://www.postman.com/downloads/

Fetch API

There are 2 high level ways a browser can send requests to an HTTP server:

notion image

  1. From the browser URL (Default GET request):

      • When you type a URL into the browser’s address bar and press Enter, the browser sends an HTTP GET request to the server. This request is used to retrieve resources like HTML pages, images, or other content.
  2. From an HTML form or JavaScript (Various request types):

      • HTML Forms: When a user submits a form on a webpage, the browser sends an HTTP request based on the form’s method attribute, which can be GET or POST. Forms with method="POST" typically send data to the server for processing (e.g., form submissions).

        • JavaScript (Fetch API): JavaScript running in the browser can make HTTP requests to a server using APIs the fetch API. These requests can be of various types (GET, POST, PUT, DELETE, etc.) and are commonly used for asynchronous data retrieval and manipulation (e.g., AJAX requests).

Fetch request examples

Server to send the request to - https://jsonplaceholder.typicode.com/posts/1 (GET request)

<!DOCTYPE html>
<html>

<body>
  <div id="posts"></div>
  <script>
    async function fetchPosts() {
      const res = await fetch("https://jsonplaceholder.typicode.com/posts/1");
      const json = await res.json();
      document.getElementById("posts").innerHTML = json.title;
    }

    fetchPosts();
  </script>
</body>

</html>

Using axios (external library)

<!DOCTYPE html>
<html>

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/1.7.6/axios.min.js"></script>
</head>

<body>
  <div id="posts"></div>
  <script>
    async function fetchPosts() {
      const res = await axios.get("https://jsonplaceholder.typicode.com/posts/1");
      document.getElementById("posts").innerHTML = res.data.title;
    }

    fetchPosts();
  </script>
</body>

</html>

Create http server:

Steps to follow

  • Initialize node project
npm init -y
  • Install dependencies
npm install express
  • Create an empty index.js
touch index.js
  • Write the code to create 4 endpoints

      import express from "express";
    
      const app = express();
    
      app.get("/sum", function(req, res) {
          const a = parseInt(req.query.a);
          const b = parseInt(req.query.b);
    
          res.json({
              ans: a + b
          })
      });
    
      app.get("/multiply", function(req, res) {
          const a = req.query.a;
          const b = req.query.b;
          res.json({
              ans: a * b
          })
      });
    
      app.get("/divide", function(req, res) {
          const a = req.query.a;
          const b = req.query.b;
          res.json({
              ans: a / b
          })
    
      });
    
      app.get("/subtract", function(req, res) {
          const a = req.query.a;
          const b = req.query.b;
          res.json({
              ans: a - b
          })
      });
    
      app.listen(3000); // which port do you want to listen
    
      #Run the index.js
    

    Test it in the browser:

      http://localhost:3000/multiply?a=3&b=2
      http://localhost:3000/sum?a=1&b=2
      http://localhost:3000/divide?a=1&b=2
      http://localhost:3000/subtract?a=1&b=2
    
0
Subscribe to my newsletter

Read articles from Neha Sawant directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Neha Sawant
Neha Sawant