Skip to content

Commit 0e5ff48

Browse files
authored
Merge pull request #219 from microsoftgraph/feature/simplify-client-creation
Feature/simplify client creation
2 parents 386efec + 15318d5 commit 0e5ff48

11 files changed

Lines changed: 108 additions & 141 deletions

‎CHANGELOG.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,14 @@ All notable changes to this project will be documented in this file.
55
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
66
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
77

8+
## [1.0.0a13] - 2023-05-25
9+
10+
### Added
11+
12+
### Changed
13+
14+
- Simplified the creation of a graph client. [#180](https://github.com/microsoftgraph/msgraph-sdk-python/issues/180)
15+
816
## [1.0.0a12] - 2023-04-19
917

1018
### Added

‎README.md‎

Lines changed: 24 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -19,60 +19,39 @@ pip install msgraph-sdk
1919

2020
Register your application by following the steps at [Register your app with the Microsoft Identity Platform](https://docs.microsoft.com/graph/auth-register-app-v2).
2121

22-
### 2.2 Create an AuthenticationProvider object
22+
### 2.2 Initialize a GraphServiceClient object
2323

24-
An instance of the **GraphServiceClient** class handles building client. To create a new instance of this class, you need to provide an instance of **AuthenticationProvider**, which can authenticate requests to Microsoft Graph.
24+
You must create **GraphServiceClient** object to make requests against the service. To create a new instance of this class, you need to provide credentials and scopes, which can authenticate requests to Microsoft Graph.
2525

2626
> **Note**: For authentication we support both `sync` and `async` credential classes from `azure.identity`. Please see the azure identity [docs](https://learn.microsoft.com/en-us/python/api/azure-identity/azure.identity?view=azure-python) for more information.
2727
2828
```py
29-
# Example using async credentials.
30-
from azure.identity.aio import DefaultAzureCredential
31-
from kiota_authentication_azure.azure_identity_authentication_provider import AzureIdentityAuthenticationProvider
32-
33-
credential=DefaultAzureCredential()
34-
auth_provider = AzureIdentityAuthenticationProvider(credential)
35-
```
36-
37-
The above example uses default scopes for [app-only access](https://learn.microsoft.com/en-us/graph/permissions-overview#delegated-permissions). If using [delegated access](https://learn.microsoft.com/en-us/graph/permissions-overview#delegated-permissions) you can provide custom scopes:
38-
39-
```py
40-
scopes = ['User.Read', 'Mail.Read']
41-
credential=DeviceCodeCredential()
42-
auth_provider = AzureIdentityAuthenticationProvider(credential, scopes=scopes)
43-
```
44-
45-
### 2.3 Initialise a GraphRequestAdapter object
46-
47-
The SDK uses an adapter object that handles the HTTP concerns. This HTTP adapter object is used to build the Graph client for making requests.
48-
49-
To initialise one using the authentication provider created in the previous step:
50-
51-
```py
52-
from msgraph import GraphRequestAdapter
53-
54-
adapter = GraphRequestAdapter(auth_provider)
55-
```
56-
57-
We currently use [HTTPX](https://www.python-httpx.org/) as our HTTP client. You can pass your custom configured `httpx.AsyncClient` using:
58-
59-
```py
60-
import httpx
61-
from msgraph import GraphRequestAdapter
62-
from msgraph_core import GraphClientFactory
29+
# Example using async credentials and application access.
30+
from azure.identity.aio import ClientSecretCredential
31+
from msgraph import GraphServiceClient
6332

64-
http_client = GraphClientFactory.create_with_default_middleware(client=httpx.AsyncClient())
65-
request_adapter = GraphRequestAdapter(auth_provider, http_client)
33+
credential = ClientSecretCredential(
34+
tenant_id='TENANT_ID',
35+
client_id='CLIENT_ID',
36+
client_secret='CLIENT_SECRET',
37+
)
38+
scopes = ['https://graph.microsoft.com/.default']
39+
client = GraphServiceClient(credentials=credential, scopes=scopes)
6640
```
6741

68-
### 2.3 Get a GraphServiceClient object
69-
70-
You must get a **GraphServiceClient** object to make requests against the service.
42+
The above example uses default scopes for [app-only access](https://learn.microsoft.com/en-us/graph/permissions-overview?tabs=http#application-permissions). If using [delegated access](https://learn.microsoft.com/en-us/graph/permissions-overview#delegated-permissions) you can provide custom scopes:
7143

7244
```py
45+
# Example using sync credentials and delegated access.
46+
from azure.identity import DeviceCodeCredential
7347
from msgraph import GraphServiceClient
7448

75-
client = GraphServiceClient(request_adapter)
49+
credential=DeviceCodeCredential(
50+
client_id='CLIENT_ID',
51+
tenant_id='TENANT_ID',
52+
)
53+
scopes = ['User.Read', 'Mail.Read']
54+
client = GraphServiceClient(credentials=credential, scopes=scopes)
7655
```
7756

7857
## 3. Make requests against the service
@@ -86,8 +65,6 @@ The following is a complete example that shows how to fetch a user from Microsof
8665
```py
8766
import asyncio
8867
from azure.identity.aio import ClientSecretCredential
89-
from kiota_authentication_azure.azure_identity_authentication_provider import AzureIdentityAuthenticationProvider
90-
from msgraph import GraphRequestAdapter
9168
from msgraph import GraphServiceClient
9269

9370
credential = ClientSecretCredential(
@@ -96,9 +73,7 @@ credential = ClientSecretCredential(
9673
'client_secret'
9774
)
9875
scopes = ['https://graph.microsoft.com/.default']
99-
auth_provider = AzureIdentityAuthenticationProvider(credential, scopes=scopes)
100-
request_adapter = GraphRequestAdapter(auth_provider)
101-
client = GraphServiceClient(request_adapter)
76+
client = GraphServiceClient(credentials=credential, scopes=scopes)
10277

10378
async def get_user():
10479
user = await client.users.by_user_id('userPrincipalName').get()
@@ -108,20 +83,16 @@ async def get_user():
10883
asyncio.run(get_user())
10984
```
11085

111-
Note that to calling `me` requires a signed-in user and therefore delegated permissions. See [Authenticating Users](https://learn.microsoft.com/en-us/python/api/overview/azure/identity-readme?view=azure-python#authenticate-users)) for more:
86+
Note that to calling `me` requires a signed-in user and therefore delegated permissions. See [Authenticating Users](https://learn.microsoft.com/en-us/python/api/overview/azure/identity-readme?view=azure-python#authenticate-users) for more:
11287

11388
```py
11489
import asyncio
11590
from azure.identity import InteractiveBrowserCredential
116-
from kiota_authentication_azure.azure_identity_authentication_provider import AzureIdentityAuthenticationProvider
117-
from msgraph import GraphRequestAdapter
11891
from msgraph import GraphServiceClient
11992

12093
credential = InteractiveBrowserCredential()
12194
scopes=['User.Read']
122-
auth_provider = AzureIdentityAuthenticationProvider(credential, scopes=scopes)
123-
request_adapter = GraphRequestAdapter(auth_provider)
124-
client = GraphServiceClient(request_adapter)
95+
client = GraphServiceClient(credentials=credential, scopes=scopes,)
12596

12697
async def me():
12798
me = await client.me.get()

‎msgraph/_version.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
VERSION: str = '1.0.0a12'
1+
VERSION: str = '1.0.0a13'

‎msgraph/graph_service_client.py‎

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,41 @@
1+
from typing import List, Optional, TYPE_CHECKING, Union'
2+
from azure.core.credentials import TokenCredential
3+
from azure.core.credentials_async import AsyncTokenCredential
4+
from kiota_authentication_azure.azure_identity_authentication_provider import AzureIdentityAuthenticationProvider
5+
from httpx import AsyncClient
6+
17
from .generated.base_graph_service_client import BaseGraphServiceClient
28
from .graph_request_adapter import GraphRequestAdapter
39

410
class GraphServiceClient(BaseGraphServiceClient):
5-
def __init__(self, request_adapter: GraphRequestAdapter) -> None:
11+
def __init__(
12+
self,
13+
credentials: Optional[Union[TokenCredential, AsyncTokenCredential]] = None,
14+
scopes: Optional[List[str]] = None,
15+
request_adapter: Optional[GraphRequestAdapter] = None
16+
17+
) -> None:
18+
"""Constructs a client instance to use for making requests to the
19+
Microsoft Graph v.1.0 API.
20+
21+
Args:
22+
credentials (Union[TokenCredential, AsyncTokenCredential]): The
23+
tokenCredential to use for authentication.
24+
scopes (Optional[List[str]]): The scopes to use for authentication.
25+
Defaults to ['https://graph.microsoft.com/.default'].
26+
request_adapter (Optional[GraphRequestAdapter], optional): The request
27+
adapter to use for requests. Defaults to None.
28+
"""
29+
30+
if not request_adapter:
31+
if not credentials:
32+
raise ValueError("Missing request adapter or valid credentials")
33+
34+
if scopes:
35+
auth_provider = AzureIdentityAuthenticationProvider(credentials, scopes)
36+
else:
37+
auth_provider = AzureIdentityAuthenticationProvider(credentials)
38+
39+
request_adapter = GraphRequestAdapter(auth_provider)
40+
641
super().__init__(request_adapter)

‎pyproject.toml‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
44

55
[project]
66
name = "msgraph-sdk"
7-
version = "1.0.0a12"
7+
version = "1.0.0a13"
88
authors = [{name = "Microsoft", email = "graphtooling+python@microsoft.com"}]
99
description = "The Microsoft Graph Python SDK"
1010
dependencies = [
@@ -59,7 +59,7 @@ pythonpath = [
5959
]
6060

6161
[tool.bumpver]
62-
current_version = "1.0.0a12"
62+
current_version = "1.0.0a13"
6363
version_pattern = "MAJOR.MINOR.PATCH[PYTAGNUM]"
6464
commit_message = "bump version {old_version} -> {new_version}"
6565
commit = true

‎samples/applications_samples.md‎

Lines changed: 5 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,22 +5,17 @@ import asyncio
55

66
from azure.identity import EnvironmentCredential
77
from kiota_abstractions.api_error import APIError
8-
from kiota_authentication_azure.azure_identity_authentication_provider import AzureIdentityAuthenticationProvider
9-
from msgraph import GraphRequestAdapter
108
from msgraph import GraphServiceClient
119

1210
# Set the event loop policy for Windows
1311
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
1412

15-
# Create authentication provider object. Used to authenticate request
16-
credential=EnvironmentCredential()
17-
auth_provider = AzureIdentityAuthenticationProvider(credential)
13+
# Create a credential object. Used to authenticate requests
14+
credentials = EnvironmentCredential()
15+
scopes = ['https://graph.microsoft.com/.default']
1816

19-
# Initialize a request adapter. Handles the HTTP concerns.
20-
request_adapter = GraphRequestAdapter(auth_provider)
21-
22-
# Get a service client.
23-
client = GraphServiceClient(request_adapter)
17+
# Create an API client with the credentials and scopes
18+
client = GraphServiceClient(credentials=credentials, scopes=scopes)
2419
```
2520

2621
## 1. LIST ALL APPLICATIONS IN THE TENANT (GET /applications)

‎samples/authentication_samples.md‎

Lines changed: 16 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -7,26 +7,21 @@ import asyncio
77

88
from azure.identity import DeviceCodeCredential
99
from kiota_abstractions.api_error import APIError
10-
from kiota_authentication_azure.azure_identity_authentication_provider import AzureIdentityAuthenticationProvider
11-
from msgraph import GraphRequestAdapter, GraphServiceClient
10+
from msgraph import GraphServiceClient
1211

1312
# Set the event loop policy for Windows
1413
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
1514

16-
# Create authentication provider object. Used to authenticate requests
15+
# Create a credential object. Used to authenticate requests
1716
credential = DeviceCodeCredential(
1817
client_id='CLIENT_ID',
1918
tenant_id='TENANT_ID',
2019
)
2120

2221
scopes = ["User.Read"]
23-
auth_provider = AzureIdentityAuthenticationProvider(credential, scopes=scopes)
2422

25-
# Initialize a request adapter with the auth provider.
26-
request_adapter = GraphRequestAdapter(auth_provider)
27-
28-
# Create an API client with the request adapter.
29-
client = GraphServiceClient(request_adapter)
23+
# Create an API client with the credentials and scopes.
24+
client = GraphServiceClient(credentials=credential, scopes=scopes)
3025

3126
# GET A USER USING THE USER ID (GET /users/{id})
3227
async def get_user():
@@ -46,22 +41,17 @@ asyncio.run(get_user())
4641
import asyncio
4742
from azure.identity import InteractiveBrowserCredential
4843
from kiota_abstractions.api_error import APIError
49-
from kiota_authentication_azure.azure_identity_authentication_provider import AzureIdentityAuthenticationProvider
50-
from msgraph import GraphRequestAdapter, GraphServiceClient
44+
from msgraph import GraphServiceClient
5145

5246
# Set the event loop policy for Windows
5347
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
5448

55-
# Create authentication provider object. Used to authenticate requests
49+
# Create a credential object. Used to authenticate requests
5650
credential = InteractiveBrowserCredential()
5751
scopes = ["User.Read"]
58-
auth_provider = AzureIdentityAuthenticationProvider(credential, scopes=scopes)
59-
60-
# Initialize a request adapter with the auth provider.
61-
request_adapter = GraphRequestAdapter(auth_provider)
6252

63-
# Create an API client with the request adapter.
64-
client = GraphServiceClient(request_adapter)
53+
# Create an API client with the credentials and scopes.
54+
client = GraphServiceClient(credentials=credential, scopes=scopes)
6555

6656
# GET A USER USING THE USER ID (GET /users/{id})
6757
async def get_user():
@@ -83,26 +73,21 @@ import asyncio
8373

8474
from azure.identity import ClientSecretCredential
8575
from kiota_abstractions.api_error import APIError
86-
from kiota_authentication_azure.azure_identity_authentication_provider import AzureIdentityAuthenticationProvider
87-
from msgraph import GraphRequestAdapter, GraphServiceClient
76+
from msgraph import GraphServiceClient
8877

8978
# Set the event loop policy for Windows
9079
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
9180

92-
# Create authentication provider object. Used to authenticate request
81+
# Create a credential object. Used to authenticate requests
9382
credential = ClientSecretCredential(
9483
tenant_id='TENANT_ID',
9584
client_id='CLIENT_ID',
9685
client_secret='CLIENT_SECRET'
9786
)
9887
scopes = ['https://graph.microsoft.com/.default']
99-
auth_provider = AzureIdentityAuthenticationProvider(credential, scopes=scopes)
10088

101-
# Initialize a request adapter with the auth provider.
102-
request_adapter = GraphRequestAdapter(auth_provider)
103-
104-
# Create an API client with the request adapter.
105-
client = GraphServiceClient(request_adapter)
89+
# Create an API client with the credentials and scopes.
90+
client = GraphServiceClient(credentials=credential, scopes=scopes)
10691

10792
# GET A USER USING THE USER ID (GET /users/{id})
10893
async def get_user():
@@ -122,22 +107,17 @@ import asyncio
122107

123108
from azure.identity.aio import EnvironmentCredential
124109
from kiota_abstractions.api_error import APIError
125-
from kiota_authentication_azure.azure_identity_authentication_provider import AzureIdentityAuthenticationProvider
126-
from msgraph import GraphRequestAdapter, GraphServiceClient
110+
from msgraph import GraphServiceClient
127111

128112
# Set the event loop policy for Windows
129113
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
130114

131-
# Create authentication provider object. Used to authenticate request
115+
# Create a credential object. Used to authenticate requests
132116
credential = EnvironmentCredential()
133117
scopes = ['https://graph.microsoft.com/.default']
134-
auth_provider = AzureIdentityAuthenticationProvider(credential, scopes=scopes)
135-
136-
# Initialize a request adapter with the auth provider.
137-
request_adapter = GraphRequestAdapter(auth_provider)
138118

139-
# Create an API client with the request adapter.
140-
client = GraphServiceClient(request_adapter)
119+
# Create an API client with the credentials and scopes.
120+
client = GraphServiceClient(credentials=credential, scopes=scopes)
141121

142122
# GET A USER USING THE USER ID (GET /users/{id})
143123
async def get_user():

‎samples/drives_samples.md‎

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,26 +5,21 @@ import asyncio
55

66
from azure.identity import ClientSecretCredential
77
from kiota_abstractions.api_error import APIError
8-
from kiota_authentication_azure.azure_identity_authentication_provider import AzureIdentityAuthenticationProvider
9-
from msgraph import GraphRequestAdapter, GraphServiceClient
8+
from msgraph import GraphServiceClient
109

1110
# (Optional) Set the event loop policy for Windows
1211
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
1312

14-
# Create authentication provider object. Used to authenticate request
13+
# Create a credential object. Used to authenticate requests
1514
credential = ClientSecretCredential(
1615
tenant_id='TENANT_ID',
1716
client_id='CLIENT_ID',
1817
client_secret='CLIENT_SECRET'
1918
)
2019
scopes = ['https://graph.microsoft.com/.default']
21-
auth_provider = AzureIdentityAuthenticationProvider(credential, scopes=scopes)
2220

23-
# Initialize a request adapter with the auth provider.
24-
request_adapter = GraphRequestAdapter(auth_provider)
25-
26-
# Create an API client with the request adapter.
27-
client = GraphServiceClient(request_adapter)
21+
# Create an API client with the credentials and scopes.
22+
client = GraphServiceClient(credentials=credential, scopes=scopes)
2823
```
2924

3025
## 1. LIST ALL DRIVES (GET /drives)

0 commit comments

Comments
 (0)