The Python Oracle

What is the quickest way to HTTP GET in Python?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game Looping

--

Chapters
00:00 Question
00:44 Accepted answer (Score 969)
01:05 Answer 2 (Score 488)
01:29 Answer 3 (Score 31)
01:47 Answer 4 (Score 20)
02:23 Thank you

--

Full question
https://stackoverflow.com/questions/6453...

Accepted answer links:
[urllib.request]: https://docs.python.org/library/urllib.r...
[read]: https://docs.python.org/tutorial/inputou...

Answer 2 links:
[Requests]: https://docs.python-requests.org/en/late.../

Answer 4 links:
[httplib2]: https://github.com/httplib2/httplib2

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #http #networking

#avk47



ACCEPTED ANSWER

Score 1014


Python 3:

import urllib.request
contents = urllib.request.urlopen("http://example.com/foo/bar").read()

Python 2:

import urllib2
contents = urllib2.urlopen("http://example.com/foo/bar").read()

Documentation for urllib.request and read.




ANSWER 2

Score 518


Use the Requests library:

import requests
r = requests.get("http://example.com/foo/bar")

Then you can do stuff like this:

>>> print(r.status_code)
>>> print(r.headers)
>>> print(r.content)  # bytes
>>> print(r.text)     # r.content as str

Install Requests by running this command:

pip install requests



ANSWER 3

Score 31


If you want solution with httplib2 to be oneliner consider instantiating anonymous Http object

import httplib2
resp, content = httplib2.Http().request("http://example.com/foo/bar")



ANSWER 4

Score 20


Have a look at httplib2, which - next to a lot of very useful features - provides exactly what you want.

import httplib2

resp, content = httplib2.Http().request("http://example.com/foo/bar")

Where content would be the response body (as a string), and resp would contain the status and response headers.

It doesn't come included with a standard python install though (but it only requires standard python), but it's definitely worth checking out.