How to use github api token in python for request

I can get the Github api token in python using username and password, but I cannot use this API token to request any POST / DELETE / PATCH.

How we use Github API tokens to execute any request. For example, I have an API token that allows you to say "hbnajkjanjknjknh23b2jk2kj2jnkl2 ..."

now for request

#i'm providing username and API-Token in headers like self.header = {'X-Github-Username': self.username, 'X-Github-API-Token': self.api_token } #then requesting(post) to create a gist r = requests.post(url, headers=headers) 

But I always get 401 error with the message Bad Crediantials .

What is the correct way to use API tokens without entering a password

+6
source share
1 answer

First, I would recommend using a wrapper for the API. You ask a lot of questions here that can be simplified by finding a wrapper whose API you rate. There is a list of wrappers written in Python here .

As for your answer to your question, it’s clear enough in the GitHub documentation that you need to send an authorization header . Your call will look like this:

 self.headers = {'Authorization': 'token %s' % self.api_token} r = requests.post(url, headers=self.headers) 

Since it seems like you're using queries and a class, can I be brave enough to make a recommendation? Say you are doing something like creating a client for an API. You might have a class like this:

 class GitHub(object): def __init__(self, **config_options): self.__dict__.update(**config_options) self.session = requests.Session() if hasattr(self, 'api_token'): self.session.headers['Authorization'] = 'token %s' % self.api_token elif hasattr(self, 'username') and hasattr(self, 'password'): self.session.auth = (self.username, self.password) def call_to_the_api(self, *args): # do stuff with args return self.session.post(url) 

The Session object will take care of authentication for you (either with tokens or with a username and password).

Also, if you decide to use github3.py for your API covers, there is a tag here.

+12
source

Source: https://habr.com/ru/post/949337/


All Articles