pythonpython-2.7github-apigist

Posting to a Gist with Github API


I've been trying to write to a gist using Python urllib2 with the following:

def _log_error(information, date=datetime.date.today(), current_time=time.strftime("%H:%M:%S")):
    log_string = """
    Info: {}
    Date: {}
    Time: {}
    """.format(information, date, current_time)
    filename = "<file>"
    token = "<token>"
    access_url = "https://api.github.com/gists/{}".format(filename)
    req = urllib2.Request(access_url)
    req.add_header("Authorization", "token {}".format(token))
    req.add_header("Content-Type", "application/json")
    json_data = {"content": log_string}
    urllib2.urlopen(req, data=json.dumps(json_data))

However, every time I try to do this, I get the following error:

Traceback (most recent call last):
  File "printer.py", line 324, in <module>
    _log_error("test")
  File "printer.py", line 69, in _log_error
    urllib2.urlopen(req, data=json.dumps(json_data))
  File "C:\Python27\lib\urllib2.py", line 154, in urlopen
    return opener.open(url, data, timeout)
  File "C:\Python27\lib\urllib2.py", line 435, in open
    response = meth(req, response)
  File "C:\Python27\lib\urllib2.py", line 548, in http_response
    'http', request, response, code, msg, hdrs)
  File "C:\Python27\lib\urllib2.py", line 473, in error
    return self._call_chain(*args)
  File "C:\Python27\lib\urllib2.py", line 407, in _call_chain
    result = func(*args)
  File "C:\Python27\lib\urllib2.py", line 556, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 422: Unprocessable Entity

What is causing this error and how can I fix it, without using an external library (such as requests)?


Solution

  • To create a gist , use Create Gist endpoint requires the following JSON format :

    {
      "description": "the description for this gist",
      "public": true,
      "files": {
        "file1.txt": {
          "content": "String file contents"
        }
      }
    }
    

    The following will map the right fields for description,public,filename and your 3 content fields info,date and current_time :

    import urllib2
    import json
    import datetime
    import time
    
    token = "YOUR_TOKEN"
    access_url = "https://api.github.com/gists"
    
    filename = "file.txt"
    description = "the description for this gist"
    public = "true"
    
    information = "some info"
    date = datetime.date.today()
    current_time = time.strftime("%H:%M:%S")
    
    data = """{
      "description": "%s",
      "public": %s,
      "files": {
        "%s": {
          "content": "info : %s,date: %s, current_time: %s"
        }
      }
    }"""
    
    json_data = data % (description, public, filename, information, date, current_time)
    
    req = urllib2.Request(access_url)
    req.add_header("Authorization", "token {}".format(token))
    req.add_header("Content-Type", "application/json")
    urllib2.urlopen(req, data=json_data)