Python github get token

khamidou / genjwt.py

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

#!/usr/bin/env python3
#
# This is an example script that generates JWT tokens for the Github API.
# Usage: genjwt.py your_github_private_key.pem
#
# After getting a token, you can make curl requests to the API like this:
# curl -i -H «Authorization: Bearer JWT_TOKEN» -H «Accept: application/vnd.github.machine-man-preview+json» «https://api.github.com/app»
import sys
import jwt
import time
from cryptography . hazmat . primitives . serialization import load_pem_private_key
from cryptography . hazmat . backends import default_backend
current_time = int ( time . time ())
payload =
# issued at time
‘iat’ : current_time ,
# JWT expiration time (10 minute maximum)
‘exp’ : current_time + ( 10 * 60 ),
# GitHub App’s identifier – you can get it from the github application dashboard
‘iss’ : YOUR_APP_IDENTIFIER ,
>
private_key_file = sys . argv [ 1 ]
with open ( private_key_file ) as fd :
private_key_contents = fd . read (). encode ()
cert_obj = load_pem_private_key ( private_key_contents , password = None , backend = default_backend ())
encoded = jwt . encode ( payload , private_key_contents , algorithm = ‘RS256’ )
print ( encoded )

Источник

Generate a Github OAuth2 Token¶

There are two ways to authenticate with the GitHub API: HTTP basic auth, and OAuth2. [1] It is preferable to use OAuth2, so your script can run without user input, and without storing your password.

The OAauth2 token can be sent in the request header, or as a parameter. We will send it as a header in later examples.

POST Request¶

First, we will prompt the user for username/password, and compose a POST request to the API. The request format is documented in the OAuth section of the Github API docs.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
GITHUB_API = 'https://api.github.com' import requests import json from urlparse import urljoin def main(): # # User Input # username = raw_input('Github username: ') password = raw_input('Github password: ') # # Compose Request # url = urljoin(GITHUB_API, 'authorizations') payload = <> res = requests.post( url, auth = (username, password), data = json.dumps(payload), ) print res.text if __name__ == '__main__': main() 
(class)$ python authtoken.py Github username: jmcvetta Github password: fooba 

That’s not good — our password is shown when we type it!

Password Privacy¶

We can protect the user’s privacy while inputting their password with the getpass library. While we’re at it, we can prompt the user for an optional note to describe how this token will be used.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
GITHUB_API = 'https://api.github.com' import requests import getpass import json from urlparse import urljoin def main(): # # User Input # username = raw_input('Github username: ') password = getpass.getpass('Github password: ')  note = raw_input('Note (optional): ')  # # Compose Request # url = urljoin(GITHUB_API, 'authorizations') payload = <> if note:  payload['note'] = note  res = requests.post( url, auth = (username, password), data = json.dumps(payload), ) print res.text if __name__ == '__main__': main() 
(class)$ python authtoken.py Github username: jmcvetta Github password: Note (optional): admin script <"scopes":[],"note_url":null,"created_at":"2012-10-21T05:32:30Z","url":"https://api.github.com/authorizations/744660","app":<"url":"http://developer.github.com/v3/oauth/#oauth-authorizations-api","name":"admin script (API)">,"updated_at":"2012-10-21T05:32:30Z","token":"a977026974077e83e593744aa9308422e92a26bd","note":"admin script","id":744660> 

Seems to have worked! The response is a big JSON blob.

JSON Parsing¶

We can parse the JSON response and provide just the token, in nice human-readable form, to the user.

Explore the response data by setting a breakpoint and running our program in the debugger. Start by parsing res.text into JSON, and examining the keys.

The token lives in the creatively-named field token . We will extract it and print it for the user.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
GITHUB_API = 'https://api.github.com' import requests import getpass import json from urlparse import urljoin def main(): # # User Input # username = raw_input('Github username: ') password = getpass.getpass('Github password: ') note = raw_input('Note (optional): ') # # Compose Request # url = urljoin(GITHUB_API, 'authorizations') payload = <> if note: payload['note'] = note res = requests.post( url, auth = (username, password), data = json.dumps(payload), ) # # Parse Response # j = json.loads(res.text)  token = j['token']  print 'New token: %s' % token  if __name__ == '__main__': main() 
(class)$ python authtoken.py Github username: jmcvetta Github password: Note (optional): admin script New token: 9c0e2ab295ee0e92130142ad3c90bbf5fe93642f 

Error Handling¶

But what if we don’t type the right username/password combo?

(class)$ python authtoken.py Github username: jmcvetta Github password: Note (optional): Traceback (most recent call last): File "authtoken.2.py", line 46, in main() File "authtoken.2.py", line 42, in main token = j['token'] KeyError: 'token' 

Once again we can run our program in the debugger to explore the server’s response. It looks like we have a res.status_code of 401. Any HTTP response code 400 or above indicates an error. It also looks like the server helpfully provides a message field with an error message.

We can look for response codes >= 400 and present the user a friendly error message:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
GITHUB_API = 'https://api.github.com' import requests import getpass import json from urlparse import urljoin def main(): # # User Input # username = raw_input('Github username: ') password = getpass.getpass('Github password: ') note = raw_input('Note (optional): ') # # Compose Request # url = urljoin(GITHUB_API, 'authorizations') payload = <> if note: payload['note'] = note res = requests.post( url, auth = (username, password), data = json.dumps(payload), ) # # Parse Response # j = json.loads(res.text) if res.status_code >= 400:  msg = j.get('message', 'UNDEFINED ERROR (no error description from server)')  print 'ERROR: %s' % msg  return  token = j['token'] print 'New token: %s' % token if __name__ == '__main__': main() 
(class)$ python authtoken.py Github username: jmcvetta Github password: Note (optional): ERROR: Bad credentials 

Now we have a friendly, useful program.

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Get a github token from multiple locations.

License

PythonCoderAS/get-github-token

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Get a github token from multiple locations.

getToken(tokenInput?: string | null, environmentVariableName = «GITHUB_TOKEN»): string | null

Gets a token from the environment or a command line argument.

  • tokenInput?: string | null — The token input from the command line.
  • environmentVariableName: string — The environment variable name to check for a token. Defaults to GITHUB_TOKEN .

Returns: string | null — The token if found, otherwise returns null .

About

Get a github token from multiple locations.

Источник

How to use github api token in python for requesting?

GitHub API is an API provided by GitHub that allows developers to access various functionalities and data of GitHub through API endpoints. To use the API, an API token is required to authenticate the API requests. In this question, the user is asking about how to use the API token in Python for API requests.

Method 1: Using API Token in API URL

To use the Github API token in Python for requesting, you can use the API token in the API URL. This can be done by appending the token to the URL as a query parameter. The following steps will guide you through the process:

Step 1: Import the requests library

api_url = 'https://api.github.com/user/repos'
api_token = 'your_api_token'
headers = 'Authorization': 'token ' + api_token>
response = requests.get(api_url, headers=headers)

Step 6: Print the response

The above code will make a GET request to the Github API with the API token as a query parameter. The response will be printed in JSON format.

You can also use the API token in the URL path instead of a query parameter. This can be done by replacing the https://api.github.com with https://@api.github.com .

api_url = 'https://@api.github.com/user/repos'

The above code will make a GET request to the Github API with the API token in the URL path. The response will be printed in JSON format.

In conclusion, using the API token in the API URL is a simple and effective way to authenticate requests to the Github API in Python.

Method 2: Setting API Token in API Request Header

How to use GitHub API token in Python for requesting?

Here are the steps to use GitHub API token in Python for requesting via «Setting API Token in API Request Header»:

import requests import json
url = 'https://api.github.com/repos/OWNER/REPO/issues'
headers = 'Authorization': 'token ' + token>
response = requests.get(url, headers=headers)
data = json.loads(response.text)
if response.status_code == 200: print('Request successful') else: print('Request failed')

Here is the complete code:

import requests import json token = 'YOUR_API_TOKEN' url = 'https://api.github.com/repos/OWNER/REPO/issues' headers = 'Authorization': 'token ' + token> response = requests.get(url, headers=headers) if response.status_code == 200: data = json.loads(response.text) print(data) else: print('Request failed')

This code sends a GET request to the GitHub API endpoint for the issues of a specific repository, using the API token to authenticate the request. The response is then parsed as JSON and printed to the console.

Note: Replace YOUR_API_TOKEN with your actual GitHub API token, and replace OWNER and REPO with the owner and repository name respectively.

Method 3: Storing API Token as Environment Variable and Accessing in Python Code

In order to use the GitHub API in your Python code, you will need to authenticate your requests with an API token. One way to do this is by storing the API token as an environment variable and accessing it in your Python code. Here are the steps to do this:

  1. First, you need to generate a personal access token from your GitHub account. You can do this by going to your account settings, selecting «Developer settings», and then «Personal access tokens». Generate a new token with the necessary permissions for your project.
  2. Next, you need to store the token as an environment variable. You can do this by adding the following line to your .bashrc or .bash_profile file: export GITHUB_API_TOKEN=»your_token_here» Make sure to replace «your_token_here» with your actual token.
  3. Once you have set the environment variable, you can access it in your Python code using the os module:
import os token = os.environ.get('GITHUB_API_TOKEN')
import requests headers = < 'Authorization': f'token ' > response = requests.get('https://api.github.com/user', headers=headers) print(response.json())

That’s it! You can now use the GitHub API in your Python code with authentication using an API token stored as an environment variable.

Источник

Читайте также:  Php несколько кнопок одной форме
Оцените статью