Search code examples
pythonoauth-2.0python-requestsmicrosoft-graph-apirequests-oauthlib

Can I set a base URL for all OAuth2Session requests?


My question is specifically regarding the Microsoft Graph API, but a more widely applicable solution would be welcome.

I have a session instantiated as follows:

# Token acquisition code left out
session = OAuth2Session(token=token)

HTTP requests with this session look like this:

# List files in OneDrive
response = session.get("https://graph.microsoft.com/v1.0/me/drive/root/children")

Is it possible to set a base URL so I can leave out the base_url each time? I would like to be able to make the call like this:

# List files in OneDrive
response = session.get("me/drive/root/children")

I was able to do this by subclassing OAuth2Session and overloading the Session.request() method, but this strikes me as the wrong approach.

# Bad hack
class GraphSession (OAuth2Session):
    def request(self, *args, **kwargs):
        if len(args) > 1: # url as non-kw arg
            args = list(args) # can't assign to a tuple
            args[1] = 'https://graph.microsoft.com/v1.0/' + args[1]
        else: # url must be a kw arg
            kwargs['url'] = 'https://graph.microsoft.com/v1.0/' + kwargs['url']
        return super(GraphSession, self).request(*args, **kwargs)

Solution

  • Take a look at this code from Python console application for Microsoft Graph sample.

    def api_endpoint(url):
        """Convert a relative path such as /me/photo/$value to a full URI based
        on the current RESOURCE and API_VERSION settings in config.py.
        """
        if urllib.parse.urlparse(url).scheme in ['http', 'https']:
            return url # url is already complete
        return urllib.parse.urljoin(f'{config.RESOURCE}/{config.API_VERSION}/',
                                    url.lstrip('/'))