Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Create GIST from your python code with python requests module and OAuth token.
'''
HTTP Reuests has following parameters:
1)Request URL
2)Header Fields
3)Parameter
4)Request body
PREREQUISITE
* head over to https://github.com/settings/tokens and generate a new token with 'gists' permissions
'''
#!/usr/bin/env python
import requests
import json
GITHUB_API="https://api.github.com"
API_TOKEN='your_token_goes_here'
#form a request URL
url=GITHUB_API+"/gists"
print("Request URL: %s"%url)
#print headers,parameters,payload
headers={'Authorization':'token %s'%API_TOKEN}
params={'scope':'gist'}
payload={
"description": "Test GIST created by python code",
"public": True,
"files": {"filename for test gist": {
"content": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
}
}}
#make a request
res=requests.post(url,headers=headers,params=params,data=json.dumps(payload))
#print response --> JSON
print("Status:", res.status_code)
print("Request URL:", res.url)
j=json.loads(res.text)
print("-------")
print("Result:", j['html_url'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment