Build API clients for Python with Microsoft identity authentication

In this tutorial, you generate an API client that uses Microsoft identity authentication to access Microsoft Graph.

Required tools

Create a project

Create a directory to contain the new project.

Add dependencies

Before you can compile and run the generated API client, you need to make sure the generated source files are part of a project with the required dependencies. Your project must have a reference to the abstraction package. Additionally, you must either use the Kiota default implementations or provide your own custom implementations of the following packages.

For this tutorial, use the default implementations.

Run the following commands to get the required dependencies.

pip install microsoft-kiota-abstractions
pip install microsoft-kiota-authentication-azure
pip install microsoft-kiota-http
pip install microsoft-kiota-serialization-json
pip install microsoft-kiota-serialization-text
pip install azure-identity

Tip

It is recommended to use a package manager/virtual environment to avoid installing packages system wide. Read more here.

Generate the API client

Kiota generates API clients from OpenAPI documents. Create a file named get-me.yml and add the following.

openapi: 3.0.3
info:
  title: Microsoft Graph get user API
  version: 1.0.0
servers:
  - url: https://graph.microsoft.com/v1.0/
paths:
  /me:
    get:
      responses:
        200:
          description: Success!
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/microsoft.graph.user"
components:
  schemas:
    microsoft.graph.user:
      type: object
      properties:
        id:
          type: string
        displayName:
          type: string

You can then use the Kiota command line tool to generate the API client classes.

kiota generate -l python -d get-me.yml -c GetUserApiClient -n client -o ./client

Register an application

To be able to authenticate with the Microsoft identity platform and get an access token for Microsoft Graph, you need to create an application registration. You can install the Microsoft Graph PowerShell SDK and use it to create the app registration, or register the app manually in the Azure Active Directory admin center.

The following instructions register an app and enable device code flow for authentication.

  1. Open a browser and navigate to the Azure Active Directory admin center. Sign in with your Azure account.

  2. Select Azure Active Directory in the left-hand navigation, then select App registrations under Manage.

  3. Select New registration. On the Register an application page, set the values as follows.

    • Set Name to Kiota Test Client.
    • Set Supported account types to Accounts in any organizational directory and personal Microsoft accounts.
    • Leave Redirect URI blank.
  4. Select Register. On the Overview page, copy the value of the Application (client) ID and save it.

  5. Select Authentication under Manage.

  6. Locate the Advanced settings section. Set the Allow public client flows toggle to Yes, then select Save.

Create the client application

Create a file in the root of the project named get_user.py and add the following code. Replace YOUR_CLIENT_ID with the client ID from your app registration.

import asyncio
from azure.identity import DeviceCodeCredential
from kiota_authentication_azure.azure_identity_authentication_provider import (
    AzureIdentityAuthenticationProvider)
from kiota_http.httpx_request_adapter import HttpxRequestAdapter
from client.get_user_api_client import GetUserApiClient

async def main():
    # You may need this if your're using asyncio on windows
    # See: https://stackoverflow.com/questions/63860576
    # asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())

    client_id = 'YOUR_CLIENT_ID'
    graph_scopes = ['User.Read']

    credential = DeviceCodeCredential(client_id)
    auth_provider = AzureIdentityAuthenticationProvider(credential, scopes=graph_scopes)

    request_adapter = HttpxRequestAdapter(auth_provider)
    client = GetUserApiClient(request_adapter)

    user_me = await client.me.get()
    print(f"Hello {user_me.display_name}, your ID is {user_me.id}")

# Run main
asyncio.run(main())

Note

This example uses the DeviceCodeCredential class. You can use any of the credential classes from the azure.identity library.

Run the application

To start the application, run the following command in your project directory.

python3 get_user.py

See also