HEAD method – Python requests

Requests library is one of the important aspects of Python for making HTTP requests to a specified URL. This article revolves around how one can make HEAD request to a specified URL using requests.head() method. Before checking out the HEAD method, let’s figure out what a Http HEAD request is –

HEAD Http Method

HEAD is a request method supported by HTTP used by the World Wide Web. The HEAD method asks for a response identical to that of a GET request, but without the response body. This is useful for retrieving meta-information written in response headers, without having to transport the entire content.

How to make HEAD request through Python Requests

Python’s requests module provides in-built method called head() for making a HEAD request to a specified URI.

Syntax –

requests.head(url, params={key: value}, args)

Example –



Let’s try making a request to httpbin’s APIs for example purposes.

filter_none

edit
close

play_arrow

link
brightness_4
code

import requests
  
# Making a HEAD request
r = requests.head('https://httpbin.org/', data ={'key':'value'})
  
# check status code for response recieved
# success code - 200
print(r)
  
# print headers of request
print(r.headers)
  
# checking if request contains any content
print(r.content)

chevron_right


save this file as request.py and through terminal run,

python request.py

Output –

head-method-python-requestts

Advanced with HEAD request

The metainformation contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information sent in response to a GET request. This method can be used for obtaining metainformation about the entity implied by the request without transferring the entity-body itself. This method is often used for testing hypertext links for validity, accessibility, and recent modification.

The response to a HEAD request MAY be cacheable in the sense that the information contained in the response MAY be used to update a previously cached entity from that resource. If the new field values indicate that the cached entity differs from the current entity (as would be indicated by a change in Content-Length, Content-MD5, ETag or Last-Modified), then the cache MUST treat the cache entry as stale.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.