Microsoft Graph Python SDK Core

repository·main·Indexed 43 days ago

https://github.com/microsoftgraph/msgraph-sdk-python-core

The foundational client library for the Microsoft Graph Python SDK, providing core components for sending native HTTP requests to the Microsoft Graph API. It includes the BaseGraphRequestAdapter for request handling, GraphClientFactory for HTTP client creation with middleware, and support for batch requests, paginated responses, and large file uploads. Version 1.5.1 requires Python 3.10+.

Tokens
7.7K
Snippets
25
Records
30
Agent score
54%

What's inside Microsoft Graph Python SDK Core

  1. Configure an Authentication Provider

    main

    To authenticate requests, you must provide an instance of AuthenticationProvider to the BaseGraphRequestAdapter.

    This library uses an asynchronous API by default and supports asyncio, anyio, or trio. When using azure.identity, you must use the asynchronous credential classes (found in azure.identity.aio).

    AzureIdentityAuthenticationProvider is a convenient implementation that sets the default scopes and allowed hosts for Microsoft Graph.

    # Using EnvironmentCredential for demonstration purposes.
    from azure.identity.aio import EnvironmentCredential
    from msgraph_core.authentication import AzureIdentityAuthenticationProvider
    
    credential = EnvironmentCredential()
    auth_provider = AzureIdentityAuthenticationProvider(credential)
  2. Make asynchronous requests to Microsoft Graph

    main

    Once the BaseGraphRequestAdapter is configured, use send_async to execute requests. You must provide a RequestInformation object containing the target URL and a type that implements Parsable (or a type provided by the full Microsoft Graph service library) to handle the response.

    import asyncio
    from kiota_abstractions.request_information import RequestInformation
    
    # request_info defines the target endpoint
    request_info = RequestInformation()
    request_info.url = 'https://graph.microsoft.com/v1.0/me'
    
    # send_async executes the request. 
    # 'User' must be a type that implements Parsable.
    user = asyncio.run(adapter.send_async(request_info, User, {}))
    print(user.display_name)
  3. Initialize the BaseGraphRequestAdapter

    main

    The BaseGraphRequestAdapter is the central class used to build the client and handle requests. It requires an auth_provider (an instance of AuthenticationProvider) during initialization.

    from msgraph_core import BaseGraphRequestAdapter
    
    adapter = BaseGraphRequestAdapter(auth_provider)
  4. Manage batch requests with BatchRequestContentCollection

    main

    The BatchRequestContentCollection class is used to manage a collection of Microsoft Graph batch request items. It automatically handles splitting requests into multiple batches based on the maximum allowed requests per batch (defined by BatchRequestContent.MAX_REQUESTS).

    Key capabilities include:

    • Adding requests: Use add_batch_request_item to add a BatchRequestItem. The collection will automatically finalize the current batch and start a new one if the limit is reached.
    • Removing requests: Use remove_batch_request_item with a specific request_id to remove an item from any existing batch.
    • Retrieving batches: Use get_batch_requests_for_execution to get the list of BatchRequestContent objects ready for execution.
    • Handling failures: Use new_batch_with_failed_requests to automatically generate a new batch containing only the requests that did not return a successful status code (e.g., non-2xx responses).
    from msgraph_core.requests.batch_request_content_collection import BatchRequestContentCollection
    from msgraph_core.requests.batch_request_item import BatchRequestItem
    
    # Initialize the collection
    collection = BatchRequestContentCollection()
    
    # Add items (the collection handles batch splitting automatically)
    collection.add_batch_request_item(BatchRequestItem(id="req1", ...))
    collection.add_batch_request_item(BatchRequestItem(id="req2", ...))
    
    # Get batches ready to be sent to the API
    batches_to_execute = collection.get_batch_requests_for_execution()
    
    # After execution, create a new batch for retrying failed requests
    failed_batch = collection.new_batch_with_failed_requests()
  5. Configure GraphTelemetryHandlerOption for telemetry

    main

    The GraphTelemetryHandlerOption class is a RequestOption used to provide configuration metadata to the GraphTelemetryHandler middleware. It allows you to specify the api_version and the sdk_version being used in requests, which can be captured by telemetry handlers for monitoring and debugging purposes.

    To use it, instantiate the class with your desired api_version (of type APIVersion) and sdk_version (a string).

    from msgraph_core.middleware.options.graph_telemetry_handler_option import GraphTelemetryHandlerOption
    
    # Create an option instance with specific versions
    telemetry_option = GraphTelemetryHandlerOption(
        api_version=your_api_version_instance,
        sdk_version="1.5.1"
    )
    
    # The option can then be passed to request methods as part of the request options
  6. Get status codes from a batch response

    main

    To quickly audit the success or failure of a batch request, use get_response_status_codes(). This method iterates through all responses in the BatchResponseContent and returns a dictionary where the keys are the request_id strings and the values are the integer HTTP status codes.

    status_codes: dict[str, int] = batch_content.get_response_status_codes()
    # Example output: {'req_1': 200, 'req_2': 403}
  7. Set the body and headers of a BatchRequestItem

    main

    You can modify the properties of a BatchRequestItem after instantiation:

    • Body: Use the .body setter. It expects a BytesIO object. The class will extract the raw bytes from the stream.
    • Headers: Use the .headers setter. It accepts a dictionary where values can be strings or lists of strings. The class handles the conversion to a comma-separated string format required for headers.
    • URL: Use set_url(url). This method automatically strips the API version (e.g., /v1.0/ or /beta/) and replaces the placeholder /users/me-token-to-replace with /me to ensure the URL is relative and correctly formatted for the batch endpoint.
    from io import BytesIO
    
    # Setting the body from a BytesIO stream
    batch_item.body = BytesIO(b'{"name": "John Doe"}')
    
    # Setting headers
    batch_item.headers = {"Content-Type": "application/json", "Custom-Header": "Value"}
    
    # Setting a relative URL
    batch_item.set_url("https://graph.microsoft.com/v1.0/me/messages")
  8. Access data in a BatchResponseItem

    main

    When processing responses from a Microsoft Graph batch request, use the BatchResponseItem class to inspect individual item results. This class provides access to the status code, headers, and the response body.

    Key properties:

    • id: The unique identifier for the specific request within the batch.
    • status: The HTTP status code returned for this specific item (e.g., 200, 400, 404).
    • headers: A dictionary of the HTTP response headers.
    • body: A BytesIO object containing the raw response body.
    • content_type: A helper property that extracts the Content-Type from the headers dictionary.
  9. Use GraphTelemetryHandler middleware

    main

    The GraphTelemetryHandler is a middleware component that automatically attaches metadata headers to outgoing Microsoft Graph requests. This metadata includes the client request ID, SDK version, host operating system, and the Python runtime environment. It only attaches these headers if the request URL matches a known Microsoft Graph endpoint (defined by NationalClouds).

    from msgraph_core.middleware.telemetry import GraphTelemetryHandler
    
    # Initialize the handler with default options
    telemetry_handler = GraphTelemetryHandler()
    
    # This handler can then be added to your request pipeline/middleware stack
  10. Process batch response content with BatchResponseContent

    main

    The BatchResponseContent class is a container for the results of a Microsoft Graph batch request. It holds a collection of BatchResponseItem objects, where each item is mapped to a unique request_id.

    You can use this class to retrieve specific responses from a batch, check status codes, or deserialize response bodies into specific types.

    Key Methods:

    • get_response_by_id(request_id, response_type=None): Retrieves a BatchResponseItem for a given ID. If response_type (a class implementing Parsable) is provided, it attempts to return the deserialized object.
    • response_body(request_id, type): Deserializes the body of a specific response into the provided Parsable type.
    • get_response_stream_by_id(request_id): Returns the response body as a BytesIO stream.
    • get_response_status_codes(): Returns a dictionary mapping request_id to its integer HTTP status code.
    from msgraph_core.requests.batch_response_content import BatchResponseContent
    # Assuming 'batch_content' is an instance of BatchResponseContent received from a batch request
    
    # 1. Get status codes for all requests in the batch
    status_codes = batch_content.get_response_status_codes()
    # Returns e.g., {'1': 200, '2': 404}
    
    # 2. Get a specific response item by ID
    item = batch_content.get_response_by_id('1')
    
    # 3. Deserialize a response body into a specific model type
    # Assuming 'User' is a Parsable model class from the service library
    type_instance = batch_content.response_body('1', User)
    
    # 4. Get the response body as a stream
    stream = batch_content.get_response_stream_by_id('1')
    content = stream.read()
  11. Override default telemetry options with request options

    main

    The GraphTelemetryHandler middleware uses GraphTelemetryHandlerOption to manage telemetry metadata. While the handler is initialized with default options, you can override these options for a specific request by passing a new GraphTelemetryHandlerOption instance into the request's middleware control. This allows you to customize telemetry behavior (like api_version or sdk_version) on a per-request basis.

    # Assuming 'request' is a GraphRequest object
    # and you want to override telemetry settings for this specific call
    from msgraph_core.middleware.telemetry import GraphTelemetryHandlerOption
    
    custom_options = GraphTelemetryHandlerOption(
        api_version=APIVersion.beta,
        sdk_version="1.0.0"
    )
    
    # Use the middleware_control to attach the custom options to the request context
    request.context.middleware_control[GraphTelemetryHandlerOption.get_key()] = custom_options