Python API
MSGraph
- class RPA.MSGraph.MSGraph(client_id: Optional[str] = None, client_secret: Optional[str] = None, token: Optional[Token] = None, refresh_token: Optional[str] = None, redirect_uri: Optional[str] = None, vault_backend: bool = False, vault_secret: Optional[str] = None, file_backend_path: Optional[Path] = WindowsPath('/temp'))
Bases:
object
The MSGraph library wraps the O365 package, giving robots the ability to access the Microsoft Graph API programmatically.
OAuth Configuration
Graph’s API primarily authenticates via the OAuth 2.0 authorization code grant flow or OpenID Connect. This library exposes the OAuth 2.0 flow for robots to authenticate on behalf of users. A user must complete an initial authentication flow with the help of our OAuth Graph Example Bot.
For best results, register an app in Azure AD and configure it as so:
The type is “Web App”.
Redirect URI should be
https://login.microsoftonline.com/common/oauth2/nativeclient
The app should be a multi-tenant app.
Accounts in any organizational directory
is checked.Has relevant permissions enabled, check the Microsoft Graph permissions reference for a list of permissions available to MS Graph apps.
- ROBOT_LIBRARY_DOC_FORMAT = 'REST'
- ROBOT_LIBRARY_SCOPE = 'GLOBAL'
- authorize_and_get_token(authorization_url: str) str
Exchanges the OAuth authorization URL obtained from
Generate OAuth Authorization URL
for an access token. This library maintains the user access token for current requests and returns the refresh token to be stored in a secure location (e.g., the Robocorp Control Room Vault).- Parameters
authorization_url – The full URL retrieved by the user after completing authorization to Microsoft.
- Returns
A refresh token which should be stored securely for future sessions.
- configure_msgraph_client(client_id: str, client_secret: str, refresh_token: Optional[str] = None, redirect_uri: Optional[str] = None) Optional[str]
Configures the MS Graph client. If a refresh token is known, it can be provided to obtain a current user token to authenticate with. A new refresh token is returned if one is provided.
- Parameters
client_id – Application client ID.
client_secret – Application client secret.
refresh_token – Authorization refresh token obtained from prior OAuth flows.
redirect_uri – Must be provided with client ID and client secret if not using the default.
- Returns
A new refresh token if one was provided, or
None
.
Creates a sharepoint list and returns the instance.
- Parameters
list_data – Dictionary with the data for the new list.
site – Site instance obtained from
Get Sharepoint Site
.
- Returns
SharePoint List that was created.
SharepointList
objects have additional properties that can be accessed with dot-notation, see examples below.
- download_file_from_onedrive(target_file: Union[File, str], to_path: Optional[Union[str, Path]] = None, name: Optional[str] = None, resource: Optional[str] = None, drive: Optional[Union[Drive, str]] = None) Path
Downloads a file from Onedrive.
The downloaded file will be saved to a local path.
- Parameters
target_file –
DriveItem
or file path of the desired file.to_path – Destination folder of the downloaded file, defaults to the current directory.
name – New name for the downloaded file, with or without extension.
resource – Name of the resource if not using default.
drive – A
Drive
object or Drive ID as a string. If not provided, will use the default drive.
- Returns
Path to the downloaded file.
Downloads file from the share link.
The downloaded file will be saved to a local path.
- Parameters
share_url – URL of the shared file
to_path – Destination folder of the downloaded file, defaults to the current directory.
name – New name for the downloaded file, with or without extension.
- Returns
The Path to the downloaded file.
Downloads file from SharePoint.
The downloaded file will be saved to a local folder.
- Parameters
target_file –
DriveItem
or file path of the desired file.site – Site instance obtained from
Get Sharepoint Site
.to_path – Destination folder of the downloaded file, defaults to the current directory.
name – New name for the downloaded file, with or without extension.
drive – A
Drive
object or a Drive ID as a string.
- Returns
Path to the downloaded file.
- download_folder_from_onedrive(target_folder: Union[Folder, str], to_path: Optional[Union[str, Path]] = None, resource: Optional[str] = None, drive: Optional[Union[Drive, str]] = None) Path
Downloads a folder from OneDrive with all of its contents, including subfolders.
Caution when downloading big folder structures. The downloaded folder will be saved to a local path.
- Parameters
target_folder –
DriveItem
or path of the desired folder.to_path – Destination folder where the download will be saved to, defaults to the current directory.
resource – Name of the resource if not using default.
drive – A
Drive
object or Drive ID as a string. If not provided, will use the default drive.
- Returns
Path to the downloaded folder.
- find_onedrive_file(search_string: str, target_folder: Optional[Union[Folder, str]] = None, include_folders: Optional[bool] = False, resource: Optional[str] = None, drive: Optional[Union[Drive, str]] = None) List[DriveItem]
Returns a list of files found in OneDrive based on the search string. If a folder is not specified, the search is done in the entire drive and may include items that were shared with the user. It is possible to pass
root
as the target folder in order to avoid this behavior.The files returned are
DriveItem
objects and they have additional properties that can be accessed with dot-notation, seeList Files In Onedrive Folder
for details.- Parameters
search_string – String used to search for file in Onedrive. Values may be matched across several fields including filename, metadata, and file content.
target_folder – Folder where to search for files.
include_folders – Boolean indicating if should return folders as well.
resource – Name of the resource if not using default.
drive – A
Drive
object or Drive ID as a string. If not provided, will use the default drive.
- Returns
List of DriveItems found based on the search string.
- generate_oauth_authorization_url(client_id: Optional[str] = None, client_secret: Optional[str] = None, redirect_uri: Optional[str] = None, scopes: Optional[list] = None) str
Generates an authorization URL which must be opened by the user to complete the OAuth flow. If no scopes are provided, the default scope is used which is all scopes defined in the
Get Scopes
keyword.- Parameters
client_id – Application client ID.
client_secret – Application client secret.
redirect_uri – Can be provided with client ID and client secret if not using the default.
scopes – A list of scopes in the form required by the API. Use the helper function
Get scopes
.
- Returns
The URL the user must follow to complete their portion of the OAuth flow.
- get_drive_instance(resource: Optional[str] = None, drive_id: Optional[str] = None) Drive
Returns the specified drive from the specified resource. If either is not provided, defaults are returned.
- Parameters
resource – Name of the resource if not using default.
drive_id – The Drive ID as a string.
- Returns
The requested
Drive
object.
- get_file_instance(drive: Union[Drive, str], file: Union[File, str]) File
Returns a
File
object from the provided drive. If aFile
object is provided, it is reobtained from the API.- Parameters
drive – A
Drive
object or Drive ID as a string. If not provided, will use the default drive.file_path – A
File
object or path as a string.
- get_folder_instance(drive: Optional[Union[Drive, str]] = None, folder: Optional[Union[Folder, str]] = None) Folder
Returns a folder object from the provided drive. If a folder object is provided, it is reobtained from the API.
- Parameters
drive – A
Drive
object or Drive ID as a string. If not provided, will use the default drive.folder – A
Folder
object or folder path as a string.
Returns the items on a SharePoint list as a table. The list is found by it’s display name.
- Parameters
list_name – Display name of the SharePoint list.
site – Site instance obtained from
Get Sharepoint Site
.
- Returns
Table or list of dicts of the items.
- get_me() User
Returns the MS Graph object representing the currently logged in user. A
User
object is returned. Properties of the user can be accessed like so:
- get_scopes(*scopes: str) list
Returns the proper scope definitions based on the provided “scope helpers”, which are enumerated below. You can pass none to get all scopes. Basic is included in all other scopes. The provided object can be passed to the
scopes
parameter when callingGenerate OAuth Authorization URL
.basic
mailbox
mailbox_shared
message_send
message_send_shared
message_all
message_all_shared
address_book
address_book_shared
address_book_all
address_book_all_shared
calendar
calendar_shared
calendar_all
calendar_shared_all
users
onedrive
onedrive_all
sharepoint
sharepoint_dl
settings_all
tasks
tasks_all
presence
- Parameters
scopes – Scopes requested. If left empty, all scopes will be returned.
- Returns
A list of Scopes which can be passed to authorization keywords.
Returns a SharePoint site.
- Parameters
args – The SharePoint site to retrieve, see documentation for different methods of defining the site.
resource – Name of the resource if not using default.
- Returns
SharePoint Site instance.
There are multiple ways of retrieving a SharePoint site:
The return is of type Site and it has additional properties that can be accessed with dot-notation. See examples below.
- list_files_in_onedrive_folder(target_folder: Optional[Union[Folder, str]] = None, include_folders: Optional[bool] = False, resource: Optional[str] = None, drive: Optional[Union[Drive, str]] = None) List[DriveItem]
Returns a list of files from the specified OneDrive folder.
The files returned are
DriveItem
objects and they have additional properties that can be accessed with dot-notation.- Parameters
target_folder – Path of the folder in Onedrive. If none is provided, will return files from the root of Onedrive.
include_folders – Boolean indicating if should return folders as well.
resource – Name of the resource if not using default.
drive – A
Drive
object or Drive ID as a string. If not provided, will use the default drive.
- Returns
List of DriveItems in the folder.
List files in the SharePoint Site drive.
If the
drive
is not set, the default Document Library will be used. Thedrive
can be obtained from the keywordList Sharepoint Site Drives
.The files returned are
DriveItem
objects and they have additional properties that can be accessed with dot-notation, seeList Files In Onedrive Folder
for details.- Parameters
site – Site instance obtained from
Get Sharepoint Site
.include_folders – Boolean indicating if should return folders as well.
drive – A
Drive
object or Drive ID as a string. If not provided, will use the default drive.target_folder – Path of the folder in the Sharepoint drive. If none is provided, will return files from the root of the drive.
- Returns
List of DriveItems present in the Site drive.
Get a list of Drives available in the SharePoint Site.
- Parameters
site – Site instance obtained from
Get Sharepoint Site
.- Returns
List of Drives present in the SharePoint Site.
- refresh_oauth_token(refresh_token: Optional[str] = None) str
Refreshes the user token using the provided
refresh_token
. The user token is retained in the library and a new refresh token is returned. If no token is provided, this keyword assumes the Robocorp Vault is being used as a backend and attempts to refresh it based on that backend.- Parameters
refresh_token – The refresh token to use to refresh the session.
- Returns
A refresh token which should be stored securely for future sessions.
- search_for_users(search_string: str, search_field: str = 'displayName', resource: str = 'users') List[User]
Returns a list of
User
objects from the Active Directory based on the provided search string.User
objects have additional properties that can be accessed with dot-notation, seeGet Me
for additional details.- Parameters
search_string – Text to search for.
search_field – Where to search. Defaults to display name.
resource – Name of the resource if not using default.
- upload_file_to_onedrive(file_path: str, target_folder: Optional[Union[Folder, str]] = None, resource: Optional[str] = None, drive: Optional[Union[Drive, str]] = None) DriveItem
Uploads a file to the specified OneDrive folder.
The uploaded file is returned as a
DriveItem
object and it has additional properties that can be accessed with dot-notation, seeList Files In Onedrive Folder
for details.- Parameters
file_path – Path of the local file being uploaded.
target_folder – Path of the folder in Onedrive.
resource – Name of the resource if not using default.
drive – A
Drive
object or Drive ID as a string. If not provided, will use the default drive.
- Returns
The newly created DriveItem.
- exception RPA.MSGraph.MSGraphAuthenticationError
Bases:
Exception
Error when authentication fails.
- args
- with_traceback()
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception RPA.MSGraph.MSGraphDownloadError
Bases:
Exception
Error when download fails.
- args
- with_traceback()
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- class RPA.MSGraph.RobocorpVaultTokenBackend
Bases:
BaseTokenBackend
A simple Token backend that saves to Robocorp vault
- check_token()
Optional Abstract method to check for the token existence
- delete_token()
Optional Abstract method to delete the token
- get_token()
Loads the token, stores it in the token property and returns it
- abstract load_token()
Abstract method that will retrieve the oauth token
- abstract save_token()
Abstract method that will save the oauth token
- serializer = <module 'json' from 'C:\\hostedtoolcache\\windows\\Python\\3.9.13\\x64\\lib\\json\\__init__.py'>
- should_refresh_token(con=None)
- This method is intended to be implemented for environments
where multiple Connection instances are running on parallel.
This method should check if it’s time to refresh the token or not. The chosen backend can store a flag somewhere to answer this question. This can avoid race conditions between different instances trying to
refresh the token at once, when only one should make the refresh.
> This is an example of how to achieve this: > 1) Along with the token store a Flag > 2) The first to see the Flag as True must transacionally update it > to False. This method then returns True and therefore the > connection will refresh the token. > 3) The save_token method should be rewrited to also update the flag > back to True always. > 4) Meanwhile between steps 2 and 3, any other token backend checking > for this method should get the flag with a False value. > This method should then wait and check again the flag. > This can be implemented as a call with an incremental backoff > factor to avoid too many calls to the database. > At a given point in time, the flag will return True. > Then this method should load the token and finally return False > signaling there is no need to refresh the token.
If this returns True, then the Connection will refresh the token. If this returns False, then the Connection will NOT refresh the token. If this returns None, then this method already executed the refresh and therefore
the Connection does not have to.
By default this always returns True
There is an example of this in the examples folder.
- Parameters
con (Connection) – the connection that calls this method. This is passed because maybe the locking mechanism needs to refresh the token within the lock applied in this method.
- Return type
bool or None
- Returns
True if the Connection can refresh the token False if the Connection should not refresh the token None if the token was refreshed and therefore the
Connection should do nothing.
- property token
The stored Token dict
- token_constructor
alias of
Token
Bases:
File
Simple class to add support for shared items. Inherits File only to bypass checks in the library.
Builds the base url of this ApiComponent :param str resource: the resource to build the base url
Discard arguments since we already have the correct URL.
Asynchronously creates a copy of this DriveItem and all it’s child elements.
- Parameters
target (drive.Folder or Drive) – target location to move to. If it’s a drive the item will be moved to the root folder.
name – a new name for the copy.
- Return type
CopyOperation
Moves this item to the Recycle Bin
- Returns
Success / Failure
- Return type
bool
Downloads this file to the local drive. Can download the file in chunks with multiple requests to the server.
- Parameters
to_path (str or Path) – a path to store the downloaded file
name (str) – the name you want the stored file to have.
chunk_size (int) – number of bytes to retrieve from each api call to the server. if auto, files bigger than SIZE_THERSHOLD will be chunked (into memory, will be however only 1 request)
convert_to_pdf (bool) – will try to download the converted pdf if file extension in ALLOWED_PDF_EXTENSIONS
output (RawIOBase) – (optional) an opened io object to write to. if set, the to_path and name will be ignored
- Returns
Success / Failure
- Return type
bool
Returns this item drive :return: Drive of this item :rtype: Drive or None
the parent of this DriveItem
- Returns
Parent of this item
- Return type
Drive or drive.Folder
Returns a list of DriveItemPermissions with the permissions granted for this DriveItem.
- Returns
List of Permissions
- Return type
list[DriveItemPermission]
Returns this Item Thumbnails. Thumbnails are not supported on SharePoint Server 2016.
- Parameters
size – request only the specified size: ej: “small”, Custom 300x400 px: “c300x400”, Crop: “c300x400_Crop”
- Returns
Thumbnail Data
- Return type
dict
Returns a version for specified id
- Returns
a version object of specified id
- Return type
DriveItemVersion
Returns a list of available versions for this item
- Returns
list of versions
- Return type
list[DriveItemVersion]
Returns if this DriveItem is a File
Returns if this DriveItem is a Folder
Returns if this DriveItem is a Image
Returns if this DriveItem is a Photo
Moves this DriveItem to another Folder. Can’t move between different Drives.
- Parameters
target (drive.Folder or DriveItem or str) – a Folder, Drive item or Item Id string. If it’s a drive the item will be moved to the root folder.
- Returns
Success / Failure
- Return type
bool
Create a new query to filter results
- Parameters
attribute (str) – attribute to apply the query for
- Returns
new Query
- Return type
Query
Create a new query to filter results
- Parameters
attribute (str) – attribute to apply the query for
- Returns
new Query
- Return type
Query
Sets the base urls for this ApiComponent :param str resource: the resource to build the base url
Sends an invitation to access or edit this DriveItem
- Parameters
recipients (list[str] or list[Contact] or str or Contact) – a string or Contact or a list of the former representing recipients of this invitation
require_sign_in (bool) – if True the recipients invited will need to log in to view the contents
send_email (bool) – if True an email will be send to the recipients
message (str) – the body text of the message emailed
share_type (str) – ‘view’: will allow to read the contents. ‘edit’ will allow to modify the contents
- Returns
link to share
- Return type
DriveItemPermission
Creates or returns a link you can share with others
- Parameters
share_type (str) – ‘view’ to allow only view access, ‘edit’ to allow editions, and ‘embed’ to allow the DriveItem to be embedded
share_scope (str) – ‘anonymous’: anyone with the link can access. ‘organization’ Only organization members can access
share_password (str) – sharing link password that is set by the creator. Optional.
share_expiration_date (str) – format of yyyy-MM-dd (e.g., 2022-02-14) that indicates the expiration date of the permission. Optional.
- Returns
link to share
- Return type
DriveItemPermission
Updates this item
- Parameters
kwargs – all the properties to be updated. only name and description are allowed at the moment.
- Returns
Success / Failure
- Return type
bool