Skip to content

Instantly share code, notes, and snippets.

@keithweaver
Created March 1, 2017 16:21
Show Gist options
  • Save keithweaver/bc712ae87f44b9e14854f525d081ad58 to your computer and use it in GitHub Desktop.
Save keithweaver/bc712ae87f44b9e14854f525d081ad58 to your computer and use it in GitHub Desktop.
HTTP Server Request using Requests for Python
# Using python 2.7?
# Open your terminal and run: pip install requests
# Using python 3?
# Open your terminal and run: pip3 install requests
# More information about the requests library can be found here: https://github.com/kennethreitz/requests
# Imports are required for both calls
import json
import requests
# Example GET Call
def exampleGet():
# This endpoint/url is a POST, so you may have to change the URL to another
# URL that supports a get request.
url = "https://keithweaver.ca/blog/posts/27/test"
result = requests.get(url)
if(result.status_code == 200):
# Since we received a 200, we did find our correct endpoint. The URL
# is returning a JSON object.
response = result.json()
# Repsonse from server is as follows:
# {
# success: true,
# message: "Yeah it worked, we could find your data!"
# }
if (response['success'] == True):
print response['msg']
else:
print 'Other'
else:
print 'Another server status code other than 200.'
# Example POST Call
def examplePost():
url = "https://keithweaver.ca/blog/posts/27/test"
# Post fields supports a dictionary
post_fields = {'parameterOne': 'bar','parameterTwo':1}
# You could also do:
# post_fields = {}
# post_fields ['parameterOne'] = 'bar'
# post_fields ['parameterTwo'] = 1
result = requests.post(url, post_fields)
if(result.status_code == 200):
response = result.json()
if (response['success'] == True):
print response['msg']
else:
print 'Other'
else:
print 'Another server status code other than 200.'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment