Sobes.tech
Junior

How does a browser send a request to an API and how does it receive a response?

sobes.tech AI

Answer from AI

The browser sends an HTTP request to the API using the HTTP/1.1 or HTTP/2 protocol. It constructs a request that includes the method (GET, POST, PUT, DELETE, etc.), the resource URL, headers (such as User-Agent, Accept, Content-Type), and, if necessary, a request body for POST and PUT methods. A TCP connection is established with the server hosting the API.

The server processes the request, performs the necessary operations (accessing the database, business logic), and forms an HTTP response. The response includes a status code (e.g., 200 OK, 404 Not Found, 500 Internal Server Error), response headers (such as Content-Type, Cache-Control), and a response body, which usually contains data in JSON or XML format.

The browser receives this response over the TCP connection, parses it (extracting the status code, headers, and body), and processes the data (for example, displaying it to the user or saving it to local storage).

Example of an HTTP GET request and response:

// Browser request
GET /api/users HTTP/1.1
Host: example.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36
Accept: application/json

// Server response
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 55

[
  { "id": 1, "name": "Alice" },
  { "id": 2, "name": "Bob" }
]