HTTP is a key to communication on the internet. Methods of HTTP protocols allow clients to send requests to the servers and servers to send responses. Every website on the World Wide Web uses HTTP requests. So, it's necessary to understand them. This article explores the concept of HTTP requests, its structure, common methods, and real-life examples. This helps in understanding the functioning of the web.
An HTTP request is a message where a client, such as a web browser, asks the host located on the server for a specific resource. Clients use URLs in HTTP requests which show the resources they want to access from the server.
Every HTTP request comprises three components namely; request line
, headers
and message body
.
A request line
is the start line in an HTTP request command. It is used to initialize an action on the server. A request line would also indicate what kind of method and version of HTTP protocol the client is using. Apart from the HTTP method, a request line also consists of a URI or URL to the path or protocol.
Request line example:
GET /index.html HTTP/1.1
Headers are right behind the request line
. They offer client’s additional information to the server. Headers include data about the host, client’s user agent, language preferences and more. Server leverages this information to identify the browser and OS version of the client. HTTP request headers
are case-sensitive, followed by a colon (:
) and a value.
HTTP request Headers example:
Host: example.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36
Accept: application/json, text/plain, */*
Accept-Language: en-US,en;q=0.9
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
The message body
in an HTTP request is used to send data to the server. They are optional. So, not every HTTP request will have a message body
. It depends on the HTTP request types the client uses. The HTTP requests that do have a message body
, usually leverage POST to send information. Mainly, the server uses the message body
to provide the requested data to the client.
An HTTP request is a way to connect the client with the server. There can be many reasons for pursuing this connection. It might be to retrieve specific resources or delete certain information on the server. The most common HTTP request methods used daily include:
The biggest use case of an HTTP request is to ask the server for a specific set of data or resources. And that is done using the GET method. Every time a user wants to go to a website or any web page, the client browser first sends a request to retrieve the required data to load that page.
The GET in HTTP is a cacheable, safe, and idempotent method. However,, using a GET method multiple times can still impact server performance. The GET Method can only bring existing data from the server to the client. It can’t make any changes to it. So, the data or the resources would be in a read-only format.
When a client wants to retrieve any information, they use the GET method, but when providing some information to the server, the client uses the HTTP POST request. Let’s say users need to submit a form or upload a file. In this case, the client’s browser has to execute the POST method in HTTP to send the data to the server.
The message body
in an HTTP request contains the data. When a client browser sends a POST request, the server processes the data. Using a POST method multiple times would result in the creation of different resources on the server.
Similar to the POST method, the PUT method also allows the client to add some information to the server. The only difference between both methods is that in POST, users submit new data whereas in PUT, they update the existing data.
When implementing the PUT request, the client has to specify the resource’s URL that it wants to update. The request also includes the updated representation of the resource in its message body
. The server would simply replace the old representation with the new one.
The PUT method is idempotent so there is no harm in implementing multiple identical PUT requests as it would yield the same result.
As the name suggests, the DELETE method helps the client delete any specific resource from the server. Employing the DELETE request helps the client instruct the server to delete the resource mentioned in the request.
Upon the DELETE request of the client, when the server successfully deletes the specified resource, it sends back a confirmation to the client. Sending multiple identical DELETE requests would yield the same result.
When the server sends back a response to an HTTP request, it is called an HTTP response. The server acts upon the request it receives from the client browser. The HTTP response would then either consist of the requested resource or valuable information regarding the requested operation.
So, like an HTTP request, an HTTP response is also made up of three components with a slight difference. The response starts with a status line
, and a request starts with a request line
.
Status Line: As the request line does in an HTTP request, the status line in the HTTP response also indicates which version of HTTP is used along with the status code and the message specifying the outcome of the request.
Headers: Headers in the HTTP response offer additional information like the date and time of response, the type of content that is sent in the message body
, details of the server and instructions on how to cache the content.
Body: The actual message or response data that the server sends to the client browser is placed in the message body
. The content could be anything from XML
, JSON
or HTML
for the web page, an image, or any other kind of requested resource.
HTTP status codes represent the status of the client’s HTTP requests. They come as a part of an HTTP server response. Every status code consists of three digital numbers where the first digit of the code indicates the class or category of the response. There are five types of code groups.
Status code group |
Description |
1xx |
Informational responses, continuing processing. |
2xx |
Success responses, requests are processed, understood and accepted. |
3xx |
Redirecting responses, suggests further action to complete the request. |
4xx |
Error responses, show what’s wrong with the request on client-side. |
5xx |
Error responses, state what went wrong with processing request on server-side. |
HTTP headers provide additional information about requests and responses. This information is critical for communication between client and server. Headers are fundamental for web browsing and app functionality. They play an important role in the following web operations:
Headers bear the identification of a server’s domain that is hosting the resources. It is helpful in scenarios where a server hosts multiple domains.
Caching
Headers like Expires
and Cache-Control
handle how browsers cache responses and intermediate proxies. It helps minimize loading time and server requests by determining how long a response needs to be stored.
Cookie Management
Headers like Set-Cookie
and Cookie
help save and send cookies respectively. They assist in tracking user behavior and maintain user sessions.
Security
Headers also play a critical role in securing web applications. An Authorization header helps with user authentication whereas a Content-Security-Policy
is used for mitigating XSS and other security risks.
Response Control
Headers like Status
inform whether the request was a success or a failure. It also provides the necessary details so the client can manage responses appropriately.
Here are a few real-life examples of how different HTTP requests are commonly used in day-to-day operations. All the examples are in Python with the use of the requests
library.
From entering a simple URL for the website to asking for a specific record from the web server, fetching data requires an HTTP GET request. Let’s say, the client wants to get the weather data of London. The implementation of GET requests in this use case would look like:
import requests
response = requests.get("https://api.example.com/data", params={"param1": "value1", "param2": "value2"})
# Print the response
print(response.status_code)
print(response.json()) # Assuming the response is in JSON format
When a user wants to create a new user in a hypothetical API. And wants to send the following JSON
data:
{
"username": "newuser",
"email": "[email protected]",
"password": "securepassword"
}
The following Python code sends a POST request with the specified data:
import requests
url = "https://api.example.com/users"
data = {
"username": "newuser",
"email": "[email protected]",
"password": "securepassword"
}
# Make the POST request
response = requests.post(url, json=data)
if response.status_code == 201:
print("User created successfully:", response.json())
else:
print("Error:", response.status_code, response.text)
When a client wants to update the information of a user with a specific ID
.
import requests
url = "https://api.example.com/users/123"
data = {
"username": "updateduser",
"email": "[email protected]"
}
# Make the PUT request
response = requests.put(url, json=data)
if response.status_code == 200:
print("User updated successfully:", response.json())
else:
print("Error:", response.status_code, response.text)
When a client wants to delete a specific user. Here’s how it will look like in Python.
import requests
url = "https://api.example.com/users/123"
# Make the DELETE request
response = requests.delete(url)
if response.status_code == 204:
print("User deleted successfully.")
else:
print("Error:", response.status_code, response.text)
HTTP requests play a critical role in web interactions. Hence, it is essential to understand various request methods and how they work. However, the key to seamless communication lies in picking a suitable method. This also enhances the efficiency of web applications.
If you want to build a web service using Python, you can rent a cloud server at competitive prices with Hostman.