Call API with OAuth


request-oauthlib is python library for calling restful api with oauth authentiation

https://requests-oauthlib.readthedocs.io/en/latest/

An example get and post is as below:


from oauthlib.oauth2 import LegacyApplicationClient

from requests_oauthlib import OAuth2Session

import json


api_url = 'https://xxx.xyz/api'

token_url = 'https://xxx.xyz/api/token.oauth2'

client_id = 'xxx'

client_secret = 'xxx'

api_user_name = 'xxx'

api_user_pwd = 'xxx'


oauth = OAuth2Session(client=LegacyApplicationClient(client_id=client_id))

token = oauth.fetch_token(

        token_url = token_url,

        username = api_user_name,

        password = api_user_pwd,

        client_secret=client_secret

        )


#a get request example

response = oauth.get(f"{api_url}/v1/getlist",)

print(response.json())


#a post request

#note the post data must be a json dump

response = oauth.post(f"{api_url}/v1/fetchmultiple",

        data = json.dumps({"names": ["abc", "efg"]}),)

print(response)