有更多的步骤来认证为每docs
提出请求
Each request must contain the following OAuth protocol parameters:
OAuth Parameter Value
oauth_consumer_key Your OAuth consumer key (from Manage API Access).
oauth_token The access token obtained (from Manage API Access).
oauth_signature_method hmac-sha1
oauth_signature The generated request signature, signed with the oauth_token_secret obtained (from Manage API Access).
oauth_timestamp Timestamp for the request in seconds since the Unix epoch.
oauth_nonce A unique string randomly generated per request.
These parameters may be passed in the HTTP (Authorization) header as URL query keys or in the POST data. Generating the OAuth signature is done by applying the HMAC-SHA1 with the oauth_token_secret. You may view your OAuth consumer key at Manage API Access. OAuth libraries are available to generate these requests.
您没有通过oauth_timestamp
这是必需的或应用HMAC-SHA1,因此您得到Invalid Signature
错误,上面的文档清楚地列出了您需要发送的内容。
import requests
import oauth2
def request(url, url_params=None):
consumer_key = ""
consumer_secret = ""
token = ""
token_secret =""
url_params = url_params or {}
consumer = oauth2.Consumer(consumer_key, consumer_secret)
oauth_request = oauth2.Request(method="GET", url=url, parameters=url_params)
oauth_request.update(
{
'oauth_nonce': oauth2.generate_nonce(),
'oauth_timestamp': oauth2.generate_timestamp(),
'oauth_token': token,
'oauth_consumer_key': consumer_key
}
)
token = oauth2.Token(token, token_secret)
oauth_request.sign_request(oauth2.SignatureMethod_HMAC_SHA1(), consumer, token)
signed_url = oauth_request.to_url()
print(u'Querying {0} ...'.format(url))
return requests.get(signed_url).json()
其中使用:
还有一个实际python yelp api,你可以使用,但让你可以使用下面基于来自example code:的request
功能例如使用oauth2
和requests
做出请求的请求您的网址输出JSON的整体负载,这开始是:
Querying http://api.yelp.com/v2/search?location=Boston&term=food ...
{'region': {'center': {'longitude': -71.05460875, 'latitude': 42.35028894954365}, 'span': {'latitude_delta': 0.0325510910039668, 'longitude_delta': 0.04668455000000904}}, 'total': 8351, 'businesses': [{'name': "Giacomo's Ristorante", 'url': 'http://www.yelp.com/biz/giacomos-ristorante-boston', 'mobile_url': 'http://m.yelp.com/biz/giacomos-ristorante-boston', 'rating_img_url_large': 'http://s3-media2.fl.yelpcdn.com/assets/2/www/img/ccf2b76faa2c/ico/stars/v1/stars_large_4.png', 'phone':
...............................................................
...............................................................
我不知道如果API支持Python 3,但是代码ABO ve已经用python3和python2进行了测试,并且它工作正常,要安装oauth2
,你可以简单地使用pip install oauth2
,如果你没有安装它,请求和请求一样。
很好的答案,非常详细。 – dotcomly
@Dotcomly,谢谢。 –
太棒了!这工作!谢谢@PadraicCunningham – freddiev4