gistlib full source code in python

There are multiple ways to gist full source code in Python, but one of the easiest and most popular method is by using the requests module to interact with the Github API. Here are the steps:

  1. Install requests module by executing pip install requests in your terminal.

  2. Import the requests module.

main.py
import requests
16 chars
2 lines
  1. Prepare the API endpoint and your authentication credentials. You can either use Github's personal access token or your Github username and password.
main.py
api_url = 'https://api.github.com/gists'
auth = ('your_username', 'your_password')
83 chars
3 lines
  1. Read the source code from your Python file.
main.py
with open('your_python_file.py', 'r') as file:
    source_code = file.read()
77 chars
3 lines
  1. Create the payload for the API request. Set public to False if you want to keep the gist to yourself.
main.py
data = {
    'files': {
        'your_python_file.py': {
            'content': source_code
        }
    },
    'public': True,
}
131 chars
9 lines
  1. Send the API request using requests.post() method.
main.py
response = requests.post(api_url, json=data, auth=auth)
56 chars
2 lines
  1. Check if the gist is created successfully by looking at the response status code. The response will also contain the URL of the created gist.
main.py
if response.status_code == 201:
    print('Gist created successfully')
    print(response.json()['html_url'])
else:
    print('Error creating gist')
    print(response.json())
176 chars
7 lines

That's it! You have just gisted your Python source code using the Github API in Python. Remember to use version control for your code and to keep your authentication credentials secret.

gistlibby LogSnag