Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Batch Requests Samples #685

Merged
merged 18 commits into from
Oct 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
3d25dce
add samples for batch request with Parsable as return type
shemogumbe Sep 11, 2024
8b988db
add samples for batch request with collection body sample
shemogumbe Sep 11, 2024
17bc625
add samples for batch requests with content
shemogumbe Sep 11, 2024
9fa9444
add samples for using custom error class on batch requests
shemogumbe Sep 11, 2024
5ad879e
Merge branch 'main' into shem/batch_requests_samples
shemogumbe Sep 11, 2024
e6a99a6
update samples
shemogumbe Sep 18, 2024
5da8793
Merge branch 'shem/batch_requests_samples' of github.com:microsoftgra…
shemogumbe Sep 18, 2024
12f22bb
remove batch content creation from batch colection sample
shemogumbe Sep 25, 2024
dc1e3e4
Update batch request with content to reflect using dictionaries inste…
shemogumbe Sep 25, 2024
7bc7a66
update batch requests content to reflect using dictionaries for requests
shemogumbe Sep 25, 2024
993b80d
feat(batch_requests): batch requests feature and samples
shemogumbe Sep 25, 2024
4786712
Merge branch 'main' into shem/batch_requests_samples
shemogumbe Sep 25, 2024
e94610e
use client.batch on samples
shemogumbe Oct 2, 2024
ac501ad
Merge branch 'shem/batch_requests_samples' of github.com:microsoftgra…
shemogumbe Oct 2, 2024
c61bb25
rename client to graph_client
shemogumbe Oct 2, 2024
3174f2d
Merge branch 'main' into shem/batch_requests_samples
shemogumbe Oct 2, 2024
f5b378b
Merge branch 'main' into shem/batch_requests_samples
shemogumbe Oct 2, 2024
1dadf66
Merge branch 'main' into shem/batch_requests_samples
shemogumbe Oct 8, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions samples/batch_requests/batch_get_response_body_as_stream.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
#pylint: disable=undefined-variable
""" Demonstrate getting response body as stream in Batch Responses"""
batch_request_content = {
batch_request_item1.id: batch_request_item1,
batch_request_item2.id: batch_request_item2
}

batch_content = BatchRequestContent(batch_request_content)


async def main():
batch_response_content = await client.batch.post(batch_request_content=batch_content)

try:
stream_response = batch_response_content.get_response_stream_by_id(batch_request_item1.id)
print(f"Stream Response: {stream_response}")
print(f"Stream Response Content: {stream_response.read()}")
except AttributeError as e:
print(f"Error getting response by ID: {e}")


asyncio.run(main())
95 changes: 95 additions & 0 deletions samples/batch_requests/batch_request_with_collection.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
#pylint: disable=undefined-variable
"""Demonstrates using the Batch request with Collection"""
import asyncio

from urllib.request import Request
from kiota_abstractions.request_information import RequestInformation

from msgraph import GraphServiceClient

from kiota_abstractions.headers_collection import HeadersCollection as RequestHeaders
from msgraph_core.requests.batch_request_item import BatchRequestItem

from msgraph_core.requests.batch_request_content import BatchRequestContent
from msgraph_core.requests.batch_request_content_collection import BatchRequestContentCollection
# Create a client
# code to create graph client

graph_client = GraphServiceClient(credentials=token, scopes=graph_scopes)

# Create a request adapter from the client
request_adapter = graph_client.request_adapter

# Create some BatchRequestItems

request_info1 = RequestInformation()
request_info1.http_method = "GET"
request_info1.url = "/me"
request_info1.headers = RequestHeaders()
request_info1.headers.add("Content-Type", "application/json")

request_info2 = RequestInformation()
request_info2.http_method = "GET"
request_info2.url = "/users"
request_info2.headers = RequestHeaders()
request_info2.headers.add("Content-Type", "application/json")

request_info3 = RequestInformation()
request_info3.http_method = "GET"
request_info3.url = "/me"
request_info3.headers = RequestHeaders()
request_info3.headers.add("Content-Type", "application/json")

# Create BatchRequestItem instances
batch_request_item1 = BatchRequestItem(request_information=request_info1)
batch_request_item2 = BatchRequestItem(request_information=request_info2)

# Add a request using RequestInformation directly
batch_request_content.add_request_information(request_info1)
print(
f"Number of requests after adding request using RequestInformation: {len(batch_request_content.requests)}"
)
print("------------------------------------------------------------------------------------")
# Create an instance of BatchRequestContentCollection
collection = BatchRequestContentCollection()
# Add request items to the collection
batch_request_item_to_add = BatchRequestItem(request_information=request_info3)
batch_request_item_to_add1 = BatchRequestItem(request_information=request_info3)
batch_request_item_to_add2 = BatchRequestItem(request_information=request_info3)
batch_request_item_to_add3 = BatchRequestItem(request_information=request_info3)
batch_request_item_to_add4 = BatchRequestItem(request_information=request_info3)

collection.add_batch_request_item(batch_request_item_to_add)
collection.add_batch_request_item(batch_request_item_to_add1)
collection.add_batch_request_item(batch_request_item_to_add2)
collection.add_batch_request_item(batch_request_item_to_add3)
collection.add_batch_request_item(batch_request_item_to_add4)

# Print the current batch requests
print("Current Batch Requests:")
for request in collection.current_batch.requests:
print(f"Request ID: {request.id}, Status Code: {request.headers}")

# Remove a request item from the collection
collection.remove_batch_request_item(batch_request_item_to_add.id)
print(f"Items left in the batch after removal: {len(collection.current_batch.requests)}")


# post a collection
async def main():

batch_response_content = await graph_client.batch.post(batch_request_content=collection)
responses = batch_response_content.get_responses()
for item in responses:
for item_body in item.responses:
print(f"Item: {item_body.id}, Status Code: {item_body.status}")
print(f"body: {item_body.body} Item headers: {item_body.headers} ")
print("-----------------------------------------------")


# Run the main function
asyncio.run(main())
64 changes: 64 additions & 0 deletions samples/batch_requests/batch_request_with_content.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
#pylint: disable=undefined-variable
"""Demonstrates using the Batch request with content"""
import asyncio

from kiota_abstractions.request_information import RequestInformation
from kiota_abstractions.method import Method
from kiota_abstractions.headers_collection import HeadersCollection as RequestHeaders

from msgraph_core.requests.batch_request_item import BatchRequestItem
from msgraph_core.requests.batch_request_content import BatchRequestContent
from msgraph_core.requests.batch_request_content_collection import BatchRequestContentCollection

from msgraph_core.requests.batch_response_content import BatchResponseContent
from msgraph_core.requests.batch_response_content_collection import BatchResponseContentCollection

# Create a client
# code to create a graph client
graph_client = GraphServiceClient(credentials=token, scopes=graph_scopes)

# Create a request adapter from the clinet
request_adapter = graph_client.request_adapter

# Create batch Items
request_info1 = RequestInformation()
request_info1.http_method = "GET"
request_info1.url = "https://graph.microsoft.com/v1.0/me"
request_info1.url = "/me"

request_info1.headers = RequestHeaders()
request_info1.headers.add("Content-Type", "application/json")

request_info2 = RequestInformation()
request_info2.http_method = "GET"
request_info2.url = "/users"
request_info2.headers = RequestHeaders()
request_info2.headers.add("Content-Type", "application/json")

batch_request_item1 = BatchRequestItem(request_information=request_info1)
batch_request_item2 = BatchRequestItem(request_information=request_info2)

# Create a batch request content
batch_request_content = {
batch_request_item1.id: batch_request_item1,
batch_request_item2.id: batch_request_item2
}
batch_content = BatchRequestContent(batch_request_content)


async def main():
batch_response_content = await graph_client.batch.post(batch_request_content=batch_content)

# Print the batch response content
print(f"Batch Response Content: {batch_response_content.responses}")
for response in batch_response_content.responses:
print(f"Request ID: {response.id}, Status: {response.status}")
print(f"Response body: {response.body}, headers: {response.headers}")
print("-------------------------------------------------------------")


asyncio.run(main())
97 changes: 97 additions & 0 deletions samples/batch_requests/batch_request_with_custom_error_class.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
#pylint: disable=undefined-variable
"""Demonstrates using the Batch request with Custom Error Class"""

import asyncio

from kiota_abstractions.request_adapter import RequestAdapter
from kiota_abstractions.serialization import Parsable
from kiota_abstractions.request_information import RequestInformation
from kiota_abstractions.method import Method
from kiota_abstractions.headers_collection import HeadersCollection as RequestHeaders

from msgraph import GraphServiceClient

from msgraph_core.requests.batch_request_item import BatchRequestItem
from msgraph_core.requests.batch_request_content import BatchRequestContent

from msgraph_core.requests.batch_response_content import BatchResponseContent
# create client
# code to create client
graph_client = GraphServiceClient(credentials=token, scopes=graph_scopes)


# Create an Error map Parsable or import it from wherever you have it
class CustomError(Parsable):

def __init__(self) -> None:
self.error_code: str = None
self.message: str = None

@staticmethod
def not_found() -> 'CustomError':
error = CustomError()
error.error_code = "404"
error.message = "Resource not found"
return error


# Create a request adapter from client
request_adapter = graph_client.request_adapter

# Create batch Items
request_info1 = RequestInformation()
request_info1.http_method = "GET"
request_info1.url = "https://graph.microsoft.com/v1.0/me"
request_info1.url = "/me"

request_info1.headers = RequestHeaders()
request_info1.headers.add("Content-Type", "application/json")

request_info2 = RequestInformation()
request_info2.http_method = "GET"
request_info2.url = "/users"
request_info2.headers = RequestHeaders()
request_info2.headers.add("Content-Type", "application/json")

# get user who does not exist to test 404 in error map
request_info3 = RequestInformation()
request_info3.http_method = "GET"
request_info3.url = "/users/random-id"
request_info3.headers = RequestHeaders()
request_info3.headers.add("Content-Type", "application/json")

# bacth request items to be added to content
batch_request_item1 = BatchRequestItem(request_information=request_info1)
batch_request_item2 = BatchRequestItem(request_information=request_info2)
batch_request_item3 = BatchRequestItem(request_information=request_info3)

# Create a BatchRequestContent
batch_request_content = {
batch_request_item1.id: batch_request_item1,
batch_request_item2.id: batch_request_item2
}

batch_content = BatchRequestContent(batch_request_content)


# Function to demonstrate the usage of BatchRequestBuilder
async def main():
error_map = {"400": CustomError, "404": CustomError.not_found}

batch_response_content = await graph_client.batch.post(
batch_request_content=batch_content, error_map=error_map
)

# Print the batch response content
print(f"Batch Response Content: {batch_response_content.responses}")
for response in batch_response_content.responses:
print(f"Request ID: {response.id}, Status: {response.status}")
print(f"Response body: {response.body}, headers: {response.headers}")
print("-------------------------------------------------------------")


asyncio.run(main())
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
#pylint: disable=undefined-variable
"""Demonstrates using the Batch request with Parsable Resposnse Type"""
import asyncio

from kiota_abstractions.request_adapter import RequestAdapter
from kiota_abstractions.request_information import RequestInformation
from kiota_abstractions.method import Method
from kiota_abstractions.headers_collection import HeadersCollection as RequestHeaders

from msgraph_core.requests.batch_request_item import BatchRequestItem
from msgraph_core.requests.batch_request_content import BatchRequestContent

# import User model to serialize to
from msgraph.generated.models.user import User
# Create a client
# code to create graph client
graph_client = GraphServiceClient(credentials=token, scopes=graph_scopes)

print(f"Graph Scopes: {graph_scopes}")

# Create a request adapter from the client
request_adapter = graph_client.request_adapter

# Create batch Items
request_info1 = RequestInformation()
request_info1.http_method = "GET"
request_info1.url = "/users/<user-id-1>"

request_info1.headers = RequestHeaders()
request_info1.headers.add("Content-Type", "application/json")

request_info2 = RequestInformation()
request_info2.http_method = "GET"
request_info2.url = "/users/<user-id-2>"
request_info2.headers = RequestHeaders()
request_info2.headers.add("Content-Type", "application/json")

# bacth request items to be added to content
batch_request_item1 = BatchRequestItem(request_information=request_info1)
batch_request_item2 = BatchRequestItem(request_information=request_info2)

# Create a batch request content
batch_request_content = {
batch_request_item1.id: batch_request_item1,
batch_request_item2.id: batch_request_item2
}

batch_content = BatchRequestContent(batch_request_content)


# Function to demonstrate the usage of BatchRequestBuilder
async def main():
batch_response_content = await graph_client.batch.post(batch_request_content=batch_content)
# response_type=User

try:
individual_response = batch_response_content.get_response_by_id(
batch_request_item1.id, User
)
print(f"Individual Response: {individual_response}")
except AttributeError as e:
print(f"Error getting response by ID: {e}")


asyncio.run(main())
25 changes: 25 additions & 0 deletions samples/batch_requests/batch_response_get_status_codes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
#pylint: disable=undefined-variable
"""Demonstrates getting status codes in Batch Responses"""
batch_request_content = {
batch_request_item1.id: batch_request_item1,
batch_request_item2.id: batch_request_item2
}

batch_content = BatchRequestContent(batch_request_content)


async def main():
batch_response_content = await client.batch.post(batch_request_content=batch_content)

try:
status_codes = batch_response_content.get_response_status_codes()
print(f"Status Codes: {status_codes}")
except AttributeError as e:
print(f"Error getting respons status codes: {e}")


asyncio.run(main())
Loading