One of my most used patterns in Python is using the Requests module.  I use it pretty much daily pulling or pushing data to various API endpoints in my code.  

The pattern below imports the module, sets up Requests and then does a try/catch to capture some errors. It then uses the data that the API responds with to print out to the terminal a bit of text.

I am using the Star Wars API [] to get the opening crawl to A New Hope.


import requests

url = ''

response = requests.get(url)

except requests.exceptions.HTTPError as errh:
    print("Oh noes.. HTTP Error: ", errh)
    # return 'HTTPError'
except requests.exceptions.ConnectionError as errc:
    print("Aw man, Error Connecting: ", errc)
    # return 'ConnectionError'
except requests.exceptions.Timeout as errt:
    print("Yikes, Timeout Error: ", errt)
    # return 'Timeout'
except requests.exceptions.RequestException as err:
    print("Doh! Something Else Happened: ", err)
    # return 'RequestException'

data = response.json()

movie_title = data['title']
crawl = data['opening_crawl']


Note: the return lines are commented out, but are there to be used within functions in future code.

Request URL for more information:

My blog posts tagged with "Python Patterns" are designed to be a quick look reference for some Python code snippets I use a lot.  They are written to be a quick starting point for future projects so I do not need to type as much.