如何使用python中的请求模块访问基于令牌的API?

2024-05-21 03:58:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从另一个API调用一个API。因此,外部API具有基于jwt令牌的身份验证

import requests
response = requests.get('http://host:port/api/users', auth= ("username","password"))

我得到一个错误:

{"error":"authentication failed: jwt parse error: token contains an invalid number of segments","code":16,"message":"authentication failed: jwt parse error: token contains an invalid number of segments","details":[]}

或者,首先我需要调用登录API,获取令牌,并在调用另一个API时在头中应用该令牌。如果是这样,那么为什么在requests.get(URL, auth=(username,password))中有“auth”参数


Tags: tokenauthanapigetauthenticationparseusername
1条回答
网友
1楼 · 发布于 2024-05-21 03:58:55

以下是(从高层角度)请求背后的机制:

当构造请求时request(method, url, **kwargs)只有方法和url参数是必需的,其余参数是可选的:

:param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.

然后从方法的角度来看:

def get(url, params=None, **kwargs):
    r"""Sends a GET request.
    :param url: URL for the new :class:`Request` object.
    :param params: (optional) Dictionary, list of tuples or bytes to send
        in the query string for the :class:`Request`.
    :param \*\*kwargs: Optional arguments that ``request`` takes.
    :return: :class:`Response <Response>` object
    :rtype: requests.Response
    """

    kwargs.setdefault('allow_redirects', True)
    return request('get', url, params=params, **kwargs)

def post(url, data=None, json=None, **kwargs):
    r"""Sends a POST request.
    :param url: URL for the new :class:`Request` object.
    :param data: (optional) Dictionary, list of tuples, bytes, or file-like
        object to send in the body of the :class:`Request`.
    :param json: (optional) json data to send in the body of the :class:`Request`.
    :param \*\*kwargs: Optional arguments that ``request`` takes.
    :return: :class:`Response <Response>` object
    :rtype: requests.Response
    """

    return request('post', url, data=data, json=json, **kwargs)

对于getpost,强制参数是url,其他参数是默认或可选的

许多web服务可能需要身份验证,如HTTP基本身份验证。这是最简单的一种,请求直接支持它

from requests.auth import HTTPBasicAuth
requests.get('http://host:port/api/users', auth=('user', 'pass'))

这和我的想法是一样的

from requests.auth import HTTPBasicAuth
requests.get('http://host:port/api/user', auth=HTTPBasicAuth('user', 'pass'))

因此,从身份验证的角度(HTTPBasicAuth、HTTPDigest身份验证、OAuth1)来看,如何实现API基本上是非常重要的。基于此,您可以使用适当的模块(在requests)进行身份验证

希望这有帮助

相关问题 更多 >