Skip to content

Instantly share code, notes, and snippets.

@bradmontgomery
Created March 16, 2018 00:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bradmontgomery/30d3270109a27c1e5f1628d95000b5bb to your computer and use it in GitHub Desktop.
Save bradmontgomery/30d3270109a27c1e5f1628d95000b5bb to your computer and use it in GitHub Desktop.
An example of using Python to talk to an API
import json
import requests # 3rd-party lib, "pip install reqeusts" to install.
from pprint import pprint
def get_stuff(payload="hello"):
"""
This function will talk to httpbin.org, via a GET request. It will send
the provided payload, and print out the http status code and the arguments
it receives from httpbin.
"""
# Use the requests library to send an HTTP GET request
resp = requests.get("http://httpbin.org/get", {'payload': payload})
print("STATUS CODE: {}".format(resp.status_code))
# The content we get back is a "bytes" object, so we need to
# decode it into a UTF8 string...
resp = resp.content.decode('utf8')
# Then we can use python's json library to convert it to a python object.
data = json.loads(resp)
# then we can print just the args we get in the response.
pprint(data['args'])
def post_stuff(payload="greetings"):
"""
This function will talk to httpbin.org via a POST request. It will send
the provided payload, and print out the http status code and the arguments
it receives from httpbin.
"""
# Use the requests library to send an HTTP POST request
resp = requests.post("http://httpbin.org/post", {'payload': payload})
print("STATUS CODE: {}".format(resp.status_code))
# The content we get back is a "bytes" object, so we need to
# decode it into a UTF8 string...
resp = resp.content.decode('utf8')
# Then we can use python's json library to convert it to a python object.
data = json.loads(resp)
# then we can print form data we get in the response.
pprint(data['form'])
if __name__ == "__main__":
print("GETting stuff...")
get_stuff()
print("\nPOSTing stuff...")
post_stuff()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment