pythonapihttpgithubgist

Python how to edit/update a GitHub gist?


I am trying to update a already created json file in a gist from a python program. The problem is, I can't figure out how to do it.

I've found this api, which I'm pretty sure is related to what I'm trying to do. I once again don't know how to use it properly though.

Also I found a wrapper for GitHub gists called "simplegists" that looked perfect for what I'm trying to do. However, it seems to be currently broken, and I and others are having problems using it( specifically this problem ).

Would anyone be kind enough to help me figure out how I can edit a gist using a GitHub authentication token, in python, or at least give me some kind of reference I can work off of? Thanks!


Solution

  • Quite some python wrappers aren't working anymore because Github discontinued password authentication to the API on November 13, 2020. The best way to proceed is by using an API token. So first get a token and select the relevant scopes ('gist').

    Then you can use a python patch request in line with the API description to update your gist with the new json file:

    import requests
    import json
    
    token='API_TOKEN'
    filename="YOUR_UPDATED_JSON_FILE.json"
    gist_id="GIST_ID"
    
    content=open(filename, 'r').read()
    headers = {'Authorization': f'token {token}'}
    r = requests.patch('https://api.github.com/gists/' + gist_id, data=json.dumps({'files':{filename:{"content":content}}}),headers=headers) 
    print(r.json())
    

    Note that this example assumes that you haven't enabled two-factor authentication.