python request with authentication (access_token)

后端 未结 5 2083
别跟我提以往
别跟我提以往 2020-11-28 06:00

I am trying to get an API query into python. The command line

curl --header \"Authorization:access_token myToken\" https://website.com/id

g

相关标签:
5条回答
  • 2020-11-28 06:26

    Have you tried the uncurl package (https://github.com/spulec/uncurl)? You can install it via pip, pip install uncurl. Your curl request returns:

    >>> uncurl "curl --header \"Authorization:access_token myToken\" https://website.com/id"
    
    requests.get("https://website.com/id",
        headers={
            "Authorization": "access_token myToken"
        },
        cookies={},
    )
    
    0 讨论(0)
  • 2020-11-28 06:29

    The requests package has a very nice API for HTTP requests, adding a custom header works like this (source: official docs):

    >>> import requests
    >>> response = requests.get(
    ... 'https://website.com/id', headers={'Authorization': 'access_token myToken'})
    

    If you don't want to use an external dependency, the same thing using urllib2 of the standard library looks like this (source: the missing manual):

    >>> import urllib2
    >>> response = urllib2.urlopen(
    ... urllib2.Request('https://website.com/id', headers={'Authorization': 'access_token myToken'})
    
    0 讨论(0)
  • 2020-11-28 06:35

    I had the same problem when trying to use a token with Github.

    The only syntax that has worked for me with Python 3 is:

    import requests
    
    myToken = '<token>'
    myUrl = '<website>'
    head = {'Authorization': 'token {}'.format(myToken)}
    response = requests.get(myUrl, headers=head)
    
    0 讨论(0)
  • 2020-11-28 06:43
    >>> import requests
    >>> response = requests.get('https://website.com/id', headers={'Authorization': 'access_token myToken'})
    

    If the above doesnt work , try this:

    >>> import requests
    >>> response = requests.get('https://api.buildkite.com/v2/organizations/orgName/pipelines/pipelineName/builds/1230', headers={ 'Authorization': 'Bearer <your_token>' })
    >>> print response.json()
    
    0 讨论(0)
  • 2020-11-28 06:47

    I'll add a bit hint: it seems what you pass as the key value of a header depends on your authorization type, in my case that was PRIVATE-TOKEN

    header = {'PRIVATE-TOKEN': 'my_token'}
    response = requests.get(myUrl, headers=header)
    
    0 讨论(0)
提交回复
热议问题