Skip to content

Instantly share code, notes, and snippets.

@wrunk
Created February 17, 2012 20:49
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save wrunk/1855363 to your computer and use it in GitHub Desktop.
Save wrunk/1855363 to your computer and use it in GitHub Desktop.
Python httplib2 POST json body with auth example
#! /usr/bin/env python
'''
This is more of a personal reference as I use json very often.
The httplib2 examples are VERY good, and you should refer to them:
http://code.google.com/p/httplib2/wiki/Examples
'''
from httplib2 import Http
try:
# For c speedups
from simplejson import loads, dumps
except ImportError:
from json import loads, dumps
# These aren't needed, just for this example
import logging
from pprint import pformat
def post_dict(url, dictionary):
'''
Pass the whole dictionary as a json body to the url.
Make sure to use a new Http object each time for thread safety.
'''
http_obj = Http()
resp, content = http.request(
uri=url,
method='POST',
headers={'Content-Type': 'application/json; charset=UTF-8'},
body=dumps(dictionary),
)
logging.info('Response dictionary")
logging.info(pformat(resp))
logging.info("Response Content Body")
logging.info(pformat(content))
def main():
# NOTE you would need to setup a webapp that can accept a json post to test this.
# Perhaps ill show a quick example in a later post
post_dict(
url='http://127.0.0.1/services/something_that_accepts_a_json_post',
dictionary={'test': 'this is only a test'}
)
if __name__ == "__main__":
main()
@nordri
Copy link

nordri commented Aug 5, 2016

Hi, I founded a little bug. This is the patch.

--- /home/nordri/apires.py
+++ /home/nordri/apires2.py
@@ -23,15 +23,15 @@
Make sure to use a new Http object each time for thread safety.
'''
http_obj = Http()

  • resp, content = http.request(
  • resp, content = http_obj.request(
    uri=url,
    method='POST',
    headers={'Content-Type': 'application/json; charset=UTF-8'},
    body=dumps(dictionary),
    )
  • logging.info('Response dictionary")
  • logging.info('Response dictionary')
    logging.info(pformat(resp))
  • logging.info("Response Content Body")
  • logging.info('Response Content Body')
    logging.info(pformat(content))

def main():

Best regards!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment