A few days back I was struggling with a login, no not a usually web login but login into some website using python-requests.  You may say what a big deal in this but what if the site is using HTTP/2.0.  Then you look at some headers like

 : authority: ""
:method: POST
:path: some path

Now you open the code and add this header to your session. but when you hit the run button, boom it throws an error. 

raise ValueError('Invalid header name %r' % (header,))

ValueError: Invalid header name b':authority'

Here is the problem, how can this header be Invalid? yes, they are when it comes to HTTP/1 this is invalid headers. first, let's learn about this type of headers. 

These are not headers at all these are the pseudo-headers fields for HTTP/2 that starts with a colon. So, in short, these are not HTTP header file.

But that was not something you want to hear, all we want is a solution. After diving deep on the internet I found a library named hyper, as requests can be used for HTTP, hyper can be used for HTTP/2. Using the library is also as easy as user requests. here is the sample code. 

Before getting started you will need to install the library, to install hyper on your system with pip. Use this command

pip install hyper

And then you can try this code.

from hyper import HTTPConnection
conn = HTTPConnection('http2bin.org:443')
conn.request('GET', '/get')
resp = conn.get_response()

Here the hyper library will automatically add the pseudo-headers, and you will be able to do your work.  

But we are much familiar with requests library, and we would love if we can use requests for making http2 requests. Then don't worry we have another solution for it. 

Hyper allows you to use the hyper library with requests. 

import requests
 from hyper.contrib import HTTP20Adapter
 s = requests.Session()
 s.mount('https://http2bin.org', HTTP20Adapter())
 r = s.get('https://http2bin.org/get')

Now with this, you will be able to make HTTP/2 requests with using your old requests library. This will mount the hyper library with the requests library and you are good to go. 

But using this also comes with some limitations, one I faced was we cant close the session. 

Source : https://hyper.readthedocs.io/en/latest/quickstart.html
Continue Reading