Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Getting started with requests HTTP library

Andrea Grandi
September 17, 2016

Getting started with requests HTTP library

requests is one of the most advanced and simple to use HTTP libraries. The presentations is going to show how to get started with it, how to consume REST APIs and last but not least how to properly mock and test our code.

Andrea Grandi

September 17, 2016
Tweet

More Decks by Andrea Grandi

Other Decks in Programming

Transcript

  1. WHO AM I • Andrea Grandi • I live in

    London (UK) • Software Developer at Government Digital Service • Python/Django developer • passionate about micro controllers, IoT, Arduino, Golang and mobile development
  2. WHAT IS REQUESTS • HTTP library for Python • Supports

    Python 2.6, 2.7 and 3.3 - 3.5 • Used by large companies in the world: Her Majesty's Government, Amazon, Google, Twilio, Runscope, Mozilla, Heroku, PayPal, etc… • Actively maintained • Easy to use
  3. PHILOSOPHY • Beautiful is better than ugly • Explicit is

    better than implicit • Simple is better than complex • Complex is better than complicated • Readability counts
  4. urllib example import urllib2 gh_url = 'https://api.github.com' req = urllib2.Request(gh_url)

    password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm() password_manager.add_password(None, gh_url, 'user', 'pass') auth_manager = urllib2.HTTPBasicAuthHandler(password_manager) opener = urllib2.build_opener(auth_manager) urllib2.install_opener(opener) handler = urllib2.urlopen(req) print(handler.getcode()) print(handler.headers.getheader('content-type'))
  5. GET with parameters import requests payload = {'key1': 'value1', 'key2':

    'value2'} r = requests.get('http://httpbin.org/get', params=payload)
  6. ALL OTHER METHODS ARE SUPPORTED • PUT • PATCH •

    HEAD • OPTIONS • DELETE (don’t worry if you don’t know some of them)
  7. Raise exceptions from error status >>> bad_r = requests.get('http://httpbin.org/status/404') >>>

    bad_r.status_code # 404 >>> bad_r.raise_for_status() Traceback (most recent call last): File "requests/models.py", line 832, in raise_for_status raise http_error requests.exceptions.HTTPError: 404 Client Error
  8. Built in JSON decoder in responses >>> import requests >>>

    r = requests.get('https://api.github.com/events') >>> r.json() [{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...
  9. Headers in response >>> r.headers { 'content-encoding': 'gzip', 'connection': 'close',

    'server': 'nginx/1.0.4', 'content-type': 'application/json' }
  10. Timeouts >>> requests.get('http://github.com', timeout=0.001) Traceback (most recent call last): File

    "<stdin>", line 1, in <module> requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)
  11. grequests import grequests urls = ['http://www.heroku.com', 'http://python-tablib.org'] rs = (grequests.get(u)

    for u in urls) >>> grequests.map(rs) [<Response [200]>, <Response [200]>]
  12. ERRORS AND EXCEPTIONS • ConnectionError: network problems, refused connection ...

    • HTTPError: raised by raise_for_status() in case of unsuccessful status • TimeOut: in case the request times out • TooManyRedirects: when request reaches the maximum number of redirections
  13. Testing with Mock class TestClient(TestCase): @mock.patch('requests.get') def test_get_example_mock(self, mock_request): mocked_response

    = mock.Mock() mocked_response.status_code = 200 expected_dict = {"example": "foo"} mocked_response.json.return_value = expected_dict mock_request.return_value = mocked_response response = client.get_example() self.assertEqual(response, expected_dict)
  14. Testing with responses @responses.activate def test_get_example_responses(self): responses.add(responses.GET, 'https://httpbin.org/get', body='{"example": "foo"}',

    status=200, content_type='application/json') response = client.get_example() self.assertEqual(response, {"example": "foo"})
  15. How to stay in touch • blog: https://www.andreagrandi.it • Twitter:

    @andreagrandi • GitHub: https://github.com/andreagrandi • email: [email protected] • IRC: Andy80 on FreeNode (#python, #django, #python-uk ) • PGP: 7238 74F6 886D 5994 323F 1781 8CFB 47AD C384 F0CC