### Example API Call with Client Links - Rust Source: https://github.com/sreeise/graph-rs-sdk/wiki/Codegen-‐-Generating-API's Illustrates an example of making API calls using the established client links, demonstrating how to navigate from a client to a linked resource and call its methods. ```rust client .team("TEAM_ID") .primary_channel() .get_primary_channels(); ``` -------------------------------- ### Rust Client API Call Example Source: https://github.com/sreeise/graph-rs-sdk/wiki/Path-Based-Clients Demonstrates how to chain client calls in Rust to access specific API resources, like getting a primary channel within a team. This showcases the SDK's fluent interface design. ```rust client .team("team-id") .primaryChannel("primary-channel-id") .get_primary_channel() ``` -------------------------------- ### Initialize GraphClient with Access Token (Rust) Source: https://context7.com/sreeise/graph-rs-sdk/llms.txt Shows how to initialize a GraphClient with an access token and make a basic API call to list users. This example demonstrates the simplest way to interact with the Microsoft Graph API using a pre-obtained access token. It relies on the `graph_rs_sdk` crate and `tokio` for asynchronous operations. ```rust use graph_rs_sdk::*; #[tokio::main] async fn main() -> GraphResult<()> { // Initialize with access token let client = GraphClient::new("ACCESS_TOKEN"); // Make a simple API call to list users let response = client .users() .list_user() .send() .await?; println!("{:#?}", response); // Parse response as JSON let body: serde_json::Value = response.json().await?; println!("{:#?}", body); Ok(()) } ``` -------------------------------- ### Initialize Graph Client with Confidential Client Application (Rust) Source: https://github.com/sreeise/graph-rs-sdk/blob/master/graph-oauth/README.md Demonstrates how to initialize a Graph client using a ConfidentialClientApplication, which handles authentication and token refresh automatically. This setup is suitable for server-side applications. ```rust let confidental_client: ConfidentialClientApplication = ...; let graph_client = Graph::from(confidential_client); ``` -------------------------------- ### Configure Schedule Write Settings (Rust) Source: https://github.com/sreeise/graph-rs-sdk/wiki/Codegen-‐-Generating-API's Configures the WriteConfiguration for the Schedule resource using a second-level builder. This example demonstrates a simpler configuration as there are no further second or third-level resources to explicitly filter. ```rust ResourceIdentity::Schedule => WriteConfiguration::second_level_builder(ResourceIdentity::Teams, resource_identity) .trim_path_start("/teams/{team-id}".to_string()) .build() .unwrap() ``` -------------------------------- ### Sending Request with Send Method in Rust Source: https://github.com/sreeise/graph-rs-sdk/blob/master/README.md Shows a practical example of using the `send()` method to retrieve drive information for the current user. It details making an asynchronous request and handling the JSON response. ```rust use graph_rs_sdk::* pub async fn get_drive_item() -> GraphResult<()> { let client = GraphClient::new("ACCESS_TOKEN"); let response = client .me() .drive() .get_drive() .send() .await?; println!(ירת{:#?}", response); let body: serde_json::Value = response.json().await?; println!(ירת{:#?}", body); Ok(()) } ``` -------------------------------- ### Create HTTP GET Request Macro Source: https://github.com/sreeise/graph-rs-sdk/wiki/Macro-Wiki The `get!` macro is used to define HTTP GET requests for specific API endpoints. It allows for specifying documentation, method name, and the URL path. Optional parameters can be included for dynamic path segments. ```rust get!( doc: "List users", name: list_user, path: "/users" ); ``` ```rust get!( doc: "Get agreementAcceptances from users", name: get_agreement_acceptances, path: "/users/{{RID}}/agreementAcceptances/{{id}}", params: agreement_acceptance_id ); ``` -------------------------------- ### OpenAPI Operation ID and Tags Example Source: https://github.com/sreeise/graph-rs-sdk/wiki/Path-Based-Clients Shows a snippet from an OpenAPI configuration defining an API endpoint for managing 'sets'. It highlights the use of 'tags' (e.g., 'sites.store') and 'operationId' (e.g., 'sites.termStore.ListSets') which are crucial for codegen in structuring the client. ```json { "/sets": { "description": "Provides operations to manage the sets property of the microsoft.graph.termStore.store entity.", "get": { "tags": [ "sites.store" ], "operationId": "sites.termStore.ListSets" } } } ``` -------------------------------- ### Get Specific User by ID using `user(id).get_user()` Source: https://github.com/sreeise/graph-rs-sdk/blob/master/README.md This code example shows how to retrieve a specific user's details by providing their unique ID. It sets up a `GraphClient` with an access token and a user ID, then sends a GET request for the user, printing the response. ```rust use graph_rs_sdk::* // For more info on users see: https://docs.microsoft.com/en-us/graph/api/resources/user?view=graph-rest-1.0 // For more examples see the examples directory on GitHub static ACCESS_TOKEN: &str = "ACCESS_TOKEN"; static USER_ID: &str = "USER_ID"; async fn get_user() -> GraphResult<()> { let client = GraphClient::new(ACCESS_TOKEN); let response = client .user(USER_ID) .get_user() .send() .await?; println!("{:#?}", response); let body: serde_json::Value = response.json().await?; println!("{:#?}", body); Ok(()) } ``` -------------------------------- ### Configure PrimaryChannel Write Settings (Rust) Source: https://github.com/sreeise/graph-rs-sdk/wiki/Codegen-‐-Generating-API's Configures the WriteConfiguration for the PrimaryChannel resource using a second-level builder. This involves trimming the starting path segment and filtering out specific sub-paths that should not be included in the PrimaryChannel client generation. ```rust ResourceIdentity::PrimaryChannel => WriteConfiguration::second_level_builder(ResourceIdentity::Teams, resource_identity) .trim_path_start("/teams/{team-id}".to_string()) .filter_path(vec!["sharedWithTeams", "messages", "members"]) .build() .unwrap() ``` -------------------------------- ### OData Query for Drive Files using graph-rs-sdk Source: https://github.com/sreeise/graph-rs-sdk/blob/master/README.md Demonstrates how to query files in a user's drive using OData query parameters with the graph-rs-sdk. This example shows how to select specific properties ('id', 'name') for files in the root of the drive. Requires an access token. ```rust use graph_rs_sdk::*; async fn create_message() -> GraphResult<()> { let client = GraphClient::new("ACCESS_TOKEN"); // Get all files in the root of the drive // and select only specific properties. let response = client .me() .drive() .get_drive() .select(&["id", "name"]) .send() .await?; println!("{:#?}", response); let body: serde_json::Value = response.json().await?; println!("{:#?}", body); Ok(()) } ``` -------------------------------- ### Get OneDrive Drive using Graph RS SDK Source: https://context7.com/sreeise/graph-rs-sdk/llms.txt This snippet demonstrates how to access OneDrive drive information using the Graph RS SDK. It retrieves the current user's drive information from the /me/drive endpoint and prints the response. ```rust use graph_rs_sdk::*; #[tokio::main] async fn main() -> GraphResult<()> { let client = GraphClient::new("ACCESS_TOKEN"); // Get current user's drive let response = client .me() .drive() .get_drive() .send() .await?; println!("{:#?}", response); let body: serde_json::Value = response.json().await?; println!("{:#?}", body); Ok(()) } ``` -------------------------------- ### Batch Requests using graph-rs-sdk Source: https://github.com/sreeise/graph-rs-sdk/blob/master/README.md Illustrates how to execute multiple Microsoft Graph API calls within a single HTTP request using the graph-rs-sdk's batch functionality. This improves efficiency by reducing the number of round trips. It requires an access token and user ID, and defines a list of GET requests for drive-related information. ```rust use graph_rs_sdk::*; static USER_ID: &str = "USER_ID"; static ACCESS_TOKEN: &str = "ACCESS_TOKEN"; async fn batch() -> GraphResult<()> { let client = GraphClient::new(ACCESS_TOKEN); let json = serde_json::json!({ "requests": [ { "id": "1", "method": "GET", "url": format!("/users/{USER_ID}/drive") }, { "id": "2", "method": "GET", "url": format!("/users/{USER_ID}/drive/root") }, { "id": "3", "method": "GET", "url": format!("/users/{USER_ID}/drive/recent") }, { "id": "4", "method": "GET", "url": format!("/users/{USER_ID}/drive/root/children") }, { "id": "5", "method": "GET", "url": format!("/users/{USER_ID}/drive/special/documents") }, ] }); let response = client.batch(&json).send().await?; let body: serde_json::Value = response.json().await?; println!("{:#?}", body); Ok(()) } ``` -------------------------------- ### Rust: Stream Paginated API Responses Source: https://github.com/sreeise/graph-rs-sdk/blob/master/README.md Demonstrates how to stream paginated API responses using the async client. The `paging().stream()` method allows processing responses as they arrive, which is beneficial for handling very large datasets without loading everything into memory at once. This example shows streaming user data and delta changes. ```rust use futures::StreamExt; use graph_rs_sdk::*; static ACCESS_TOKEN: &str = "ACCESS_TOKEN"; pub async fn stream_next_links() -> GraphResult<()> { let client = GraphClient::new(ACCESS_TOKEN); let mut stream = client .users() .list_user() .select(&["id", "userPrincipalName"]) .paging() .stream::()?; while let Some(result) = stream.next().await { let response = result?; println!("{:#?}", response); let body = response.into_body(); println!("{:#?}", body); } Ok(()) } pub async fn stream_delta() -> GraphResult<()> { let client = GraphClient::new(ACCESS_TOKEN); let mut stream = client .users() .delta() .paging() .stream::()?; while let Some(result) = stream.next().await { let response = result?; println!("{:#?}", response); let body = response.into_body(); println!("{:#?}", body); } Ok(()) } ``` -------------------------------- ### Handle Interactive Auth Events with Convenience Method (Rust) Source: https://github.com/sreeise/graph-rs-sdk/blob/master/examples/interactive_auth/INTERACTIVE_AUTH.md This Rust function utilizes the `into_credential_builder` convenience method to simplify handling interactive authentication events. It abstracts away the direct management of `WebViewAuthorizationEvent`, returning a CredentialBuilder directly. This example assumes client secret authentication. ```rust async fn authenticate(tenant_id: &str, client_id: &str, client_secret: &str, redirect_uri: url::Url) -> anyhow::Result<()> { let (authorization_response, credential_builder) = AuthorizationCodeCredential::authorization_url_builder(client_id) .with_tenant(tenant_id) .with_scope(vec!["user.read"]) .with_offline_access() // Adds offline_access as a scope which is needed to get a refresh token. .with_redirect_uri(redirect_uri) .with_interactive_auth(Secret(client_secret.to_string()), Default::default()) .into_credential_builder()?; Ok(()) } ``` -------------------------------- ### Initiate Authorization URL for Token Refresh (Rust) Source: https://github.com/sreeise/graph-rs-sdk/blob/master/graph-oauth/README.md Generates an authorization URL for obtaining a refresh token, essential for automatic token refresh. This example uses the `offline_access` scope and is applicable when using `ConfidentialClientApplication`. It returns a URL that the user needs to visit to grant permissions. ```rust async fn authenticate(client_id: &str, tenant: &str, redirect_uri: url::Url) { let scope = vec!["offline_access"]; let mut credential_builder = ConfidentialClientApplication::builder(client_id) .auth_code_url_builder() .with_tenant(tenant) .with_scope(scope) // Adds offline_access as a scope which is needed to get a refresh token. .with_redirect_uri(redirect_uri) .url(); // ... add any other parameters you need } ``` -------------------------------- ### Access OneDrive using Drive ID and Item Path in Rust Source: https://github.com/sreeise/graph-rs-sdk/blob/master/README.md This example demonstrates how to interact with OneDrive using the graph-rs-sdk, accessing drives either by ID or through specific drives for me, sites, users, and groups. It includes listing drives and retrieving items by ID. The code relies on the graph-rs-sdk and serde_json crates and performs asynchronous operations. ```rust use graph_rs_sdk::*; async fn drives() -> GraphResult<()> { let client = GraphClient::new("ACCESS_TOKEN"); let response = client .drives() .list_drive() .send() .await .unwrap(); println!("{:#?}", response); let body: serde_json::Value = response.json().await?; println!("{:#?}", body); let response = client .drive("DRIVE-ID") .item("ITEM_ID") .get_items() .send() .await?; println!("{:#?}", response); let body: serde_json::Value = response.json().await?; println!("{:#?}", body); Ok(()) } ``` -------------------------------- ### Execute Multiple API Calls in a Single HTTP Request with Rust Source: https://context7.com/sreeise/graph-rs-sdk/llms.txt This code example shows how to execute multiple API calls in a single HTTP request using batching. It utilizes the `graph_rs_sdk` and `tokio` crates. The input is an access token and a JSON payload defining the batch requests, with the output being the consolidated JSON response. ```rust use graph_rs_sdk::* #[tokio::main] async fn main() -> GraphResult<()> { let client = GraphClient::new("ACCESS_TOKEN"); // Batch multiple requests together let json = serde_json::json!({ "requests": [ { "id": "1", "method": "GET", "url": "/users/USER_ID/drive" }, { "id": "2", "method": "GET", "url": "/users/USER_ID/drive/root" }, { "id": "3", "method": "GET", "url": "/users/USER_ID/drive/recent" }, { "id": "4", "method": "GET", "url": "/users/USER_ID/drive/root/children" }, { "id": "5", "method": "GET", "url": "/users/USER_ID/drive/special/documents" }, ] }); let response = client.batch(&json).send().await?; let body: serde_json::Value = response.json().await?; println!("{:#?}", body); Ok(()) } ``` -------------------------------- ### Implement Graph Client Methods Macro Source: https://github.com/sreeise/graph-rs-sdk/wiki/Macro-Wiki The `api_client_impl!` macro generates methods that serve as the entry points for initiating Graph API calls. These methods are responsible for creating instances of ApiClient structs using their respective `new` methods. ```rust api_client_impl!(admin, AdminApiClient); api_client_impl!(app_catalogs, AppCatalogsApiClient); ``` ```rust api_client_impl!( agreement_acceptances, // Method Name AgreementAcceptancesApiClient, // ApiClient agreement_acceptance, // MethodName AgreementAcceptancesIdApiClient // IdApiClient ); ``` -------------------------------- ### Authorization Code Secret With Proof Key Code Exchange (Rust) Source: https://github.com/sreeise/graph-rs-sdk/wiki/Identity-Platform-SDK-User-Guide-Pre‐Release-Only Demonstrates how to generate a sign-in URL for the authorization code grant flow with Proof Key for Code Exchange (PKCE). It includes functions for building the authorization URL and a confidential client application. Dependencies include graph_rs_sdk, lazy_static, and url. ```rust use graph_rs_sdk::identity::{ AuthorizationCodeCredential, ConfidentialClientApplication, GenPkce, ProofKeyCodeExchange, TokenCredentialExecutor, }; use lazy_static::lazy_static; use url::Url; // You can also pass your own values for PKCE instead of automatic generation by // calling ProofKeyCodeExchange::new(code_verifier, code_challenge, code_challenge_method) lazy_static! { static ref PKCE: ProofKeyCodeExchange = ProofKeyCodeExchange::oneshot().unwrap(); } fn authorization_sign_in_url(client_id: &str, redirect_uri: url::Url, scope: Vec) -> anyhow::Result { Ok(AuthorizationCodeCredential::authorization_url_builder(client_id) .with_scope(scope) .with_redirect_uri(redirect_uri) .with_pkce(&PKCE) .url()?) } fn build_confidential_client( authorization_code: &str, client_id: &str, client_secret: &str, redirect_uri: url::Url, scope: Vec, ) -> anyhow::Result> { Ok(ConfidentialClientApplication::builder(client_id) .with_auth_code(authorization_code) .with_client_secret(client_secret) .with_scope(scope) .with_redirect_uri(redirect_uri) .with_pkce(&PKCE) .build()) } ``` -------------------------------- ### Access Microsoft Graph Beta API Features with Rust Source: https://context7.com/sreeise/graph-rs-sdk/llms.txt This snippet demonstrates how to use the Microsoft Graph Beta API endpoint for accessing preview features. It requires `graph_rs_sdk` and `tokio`. The input is an access token, and the output is a JSON response from the beta endpoint. ```rust use graph_rs_sdk::* #[tokio::main] async fn main() -> GraphResult<()> { let mut client = GraphClient::new("ACCESS_TOKEN"); // Switch to beta endpoint let response = client.beta() .users() .list_user() .send() .await?; println!("{:#?}", response); let body: serde_json::Value = response.json().await?; println!("{:#?}", body); Ok(()) } ``` -------------------------------- ### OpenAPI Operation ID with Suffix Example Source: https://github.com/sreeise/graph-rs-sdk/wiki/Path-Based-Clients Presents an example of OpenAPI operation IDs that include arbitrary suffixes (e.g., '-7554', '-fba7'). This inconsistency in naming can complicate code generation and requires specific handling to ensure correct method identification. ```yaml operation_id: "reports.getTeamsUserActivityUserDetail-7554", operation_id: "reports.getTeamsUserActivityUserDetail-fba7" ``` -------------------------------- ### Build Graph Client with Confidential Client Application (Rust) Source: https://github.com/sreeise/graph-rs-sdk/wiki/Identity-Platform-SDK-User-Guide-Pre‐Release-Only Demonstrates how to construct a GraphClient using a ConfidentialClientApplication configured with ClientSecretCredential. This client is then used to make requests to the Microsoft Graph API. ```rust fn build_client(confidential_client: ConfidentialClientApplication) { let graph_client = GraphClient::from(&confidential_client); } ``` -------------------------------- ### Get User Inbox Messages using graph-rs-sdk Source: https://github.com/sreeise/graph-rs-sdk/blob/master/README.md Retrieves the top two messages from a user's inbox using the graph-rs-sdk. It requires an access token and the user ID. The function sends a GET request and prints both the raw response and the parsed JSON body. ```rust use graph_rs_sdk::*; static ACCESS_TOKEN: &str = "ACCESS_TOKEN"; static USER_ID: &str = "USER_ID"; async fn get_user_inbox_messages() -> GraphResult<()> { let client = GraphClient::new(ACCESS_TOKEN); let response = client .user(USER_ID) .mail_folder("Inbox") .messages() .list_messages() .top("2") .send() .await?; println!("{:#?}", response); let body: serde_json::Value = response.json().await?; println!("{:#?}", body); Ok(()) } ``` -------------------------------- ### Get Agreement Acceptances API Source: https://github.com/sreeise/graph-rs-sdk/wiki/Macro-Wiki Retrieves agreement acceptances for a specific user or for a specific agreement acceptance. ```APIDOC ## GET /users/{{RID}}/agreementAcceptances/{{id}} ### Description Retrieves agreement acceptances associated with a user or a specific agreement acceptance by ID. ### Method GET ### Endpoint /users/{userId}/agreementAcceptances/{agreementAcceptanceId} ### Parameters #### Path Parameters - **RID** (string) - Required - The internal identifier for the user. - **id** (string) - Required - The identifier for the agreement acceptance. #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **agreementAcceptance** (object) - The agreement acceptance object. #### Response Example ```json { "id": "acceptance1", "userId": "user1", "agreementId": "agreement1", "acceptanceDateTime": "2023-10-27T10:00:00Z" } ``` ``` -------------------------------- ### Get Available Extension Properties API Source: https://github.com/sreeise/graph-rs-sdk/wiki/Macro-Wiki Invokes the getAvailableExtensionProperties action for users, which retrieves available extension properties. ```APIDOC ## POST /users/getAvailableExtensionProperties ### Description Invokes the getAvailableExtensionProperties action for users to retrieve available extension properties. ### Method POST ### Endpoint /users/getAvailableExtensionProperties ### Parameters #### Query Parameters None #### Request Body - **requestBody** (object) - Required - The request body for the action, typically containing parameters for filtering extension properties. ### Request Example ```json { "requestBody": { "onBehalfOfId": "some-guid" } } ``` ### Response #### Success Response (200) - **extensionProperties** (array) - A list of available extension properties. #### Response Example ```json { "extensionProperties": [ { "id": "extension1", "name": "customProperty1" } ] } ``` ``` -------------------------------- ### Implement Authorization Code Grant Flow (Rust) Source: https://context7.com/sreeise/graph-rs-sdk/llms.txt Demonstrates the interactive authentication flow using the authorization code grant. This involves generating an authorization URL, exchanging the authorization code for tokens, and then using the client. The code shows how to build the authorization URL and create a `GraphClient` after receiving the authorization code. ```rust use graph_rs_sdk::identity::{AuthorizationCodeCredential, ConfidentialClientApplication}; use graph_rs_sdk::*; use url::Url; // Step 1: Generate authorization URL for user sign-in fn authorization_sign_in_url(client_id: &str, redirect_uri: Url, scope: Vec) -> Url { AuthorizationCodeCredential::authorization_url_builder(client_id) .with_redirect_uri(redirect_uri) .with_scope(scope) .url() .unwrap() } // Step 2: Exchange authorization code for tokens async fn auth_code_grant( authorization_code: &str, client_id: &str, client_secret: &str, scope: Vec, redirect_uri: Url, ) -> anyhow::Result { let mut confidential_client = ConfidentialClientApplication::builder(client_id) .with_auth_code(authorization_code) .with_client_secret(client_secret) .with_scope(scope) .with_redirect_uri(redirect_uri) .build(); let graph_client = GraphClient::from(&confidential_client); Ok(graph_client) } #[tokio::main] async fn main() -> anyhow::Result<()> { let redirect_uri = Url::parse("http://localhost:8000/redirect")?; let scope = vec!["User.Read".to_string(), "Files.ReadWrite".to_string()]; // Get the URL to redirect user for sign-in let auth_url = authorization_sign_in_url("CLIENT_ID", redirect_uri.clone(), scope.clone()); println!("Navigate to: {}", auth_url); // After user signs in, you receive authorization_code in redirect let client = auth_code_grant("AUTH_CODE", "CLIENT_ID", "CLIENT_SECRET", scope, redirect_uri).await?; // Use the client let response = client.me().get_user().send().await?; println!("{:#?}", response); Ok(()) } ``` -------------------------------- ### Access Drive Items for Me, Users, and Sites using Graph RS SDK Source: https://github.com/sreeise/graph-rs-sdk/blob/master/README.md These functions demonstrate how to access and retrieve drive items for the current user (me), specific users, and sites using the Graph RS SDK. Each function initializes a GraphClient, accesses the drive, specifies an item by ID, retrieves the items, and prints the response and body. ```rust async fn drive_me() -> GraphResult<()> { let client = GraphClient::new("ACCESS_TOKEN"); let response = client .me() .drive() .item("ITEM_ID") .get_items() .send() .await?; println!("{:#?}", response); let body: serde_json::Value = response.json().await?; println!("{:#?}", body); Ok(()) } ``` ```rust async fn drive_users() -> GraphResult<()> { let client = GraphClient::new("ACCESS_TOKEN"); let response = client .user("USER_ID") .drive() .item("ITEM_ID") .get_items() .send() .await?; println!("{:#?}", response); let body: serde_json::Value = response.json().await?; println!("{:#?}", body); Ok(()) } ``` ```rust async fn drive_users() -> GraphResult<()> { let client = GraphClient::new("ACCESS_TOKEN"); let response = client .site("SITE_ID") .drive() .item("ITEM_ID") .get_items() .send() .await?; println!("{:#?}", response); let body: serde_json::Value = response.json().await?; println!("{:#?}", body); Ok(()) } ``` -------------------------------- ### List User Channels with Paging in Rust Source: https://github.com/sreeise/graph-rs-sdk/blob/master/README.md This snippet demonstrates how to list user channels using the graph-rs-sdk and handles paging to retrieve all channels. It initializes a GraphClient, retrieves channels, and prints the response body. The code depends on the graph-rs-sdk crate and uses asynchronous operations. ```rust use graph_rs_sdk::*; static ACCESS_TOKEN: &str = "ACCESS_TOKEN"; async fn channel_next_links() -> GraphResult<()> { let client = GraphClient::new(ACCESS_TOKEN); let mut receiver = client .users() .list_user() .paging() .channel::() .await?; while let Some(result) = receiver.recv().await { match result { Ok(response) => { println!("{:#?}", response); let body = response.into_body(); println!("{:#?}", body); } Err(err) => panic!("{:#?}", err), } } Ok(()) } ``` -------------------------------- ### Build GraphClient with Client Secret Credential (Rust) Source: https://github.com/sreeise/graph-rs-sdk/blob/master/examples/identity_platform_auth/README.md Initializes a GraphClient using the Client Secret Credential flow, suitable for server-to-server interactions. This method requires the client ID, client secret, and tenant ID. It leverages the `ConfidentialClientApplication` builder from the `graph_rs_sdk`. ```rust use graph_rs_sdk::{oauth::ConfidentialClientApplication, GraphClient}; pub async fn build_client(client_id: &str, client_secret: &str, tenant: &str) -> GraphClient { let mut confidential_client_application = ConfidentialClientApplication::builder(client_id) .with_client_secret(client_secret) .with_tenant(tenant) .build(); GraphClient::from(&confidential_client_application) } ``` -------------------------------- ### Mail - Get Inbox Messages with Query Options using Rust Source: https://context7.com/sreeise/graph-rs-sdk/llms.txt Retrieves messages from a specific user's inbox, allowing for query options such as limiting the number of results. This requires an access token, user ID, and mail folder name. ```rust use graph_rs_sdk::*; #[tokio::main] async fn main() -> GraphResult<()> { let client = GraphClient::new("ACCESS_TOKEN"); // Get top 2 messages from inbox let response = client .user("USER_ID") .mail_folder("Inbox") .messages() .list_messages() .top("2") .send() .await?; println!("{:#?}", response); let body: serde_json::Value = response.json().await?; println!("{:#?}", body); Ok(()) } ``` -------------------------------- ### Add Resource Settings for Teams - Rust Source: https://github.com/sreeise/graph-rs-sdk/wiki/Codegen-‐-Generating-API's Sets up resource settings for Teams, including necessary imports and API client links to child resources like PrimaryChannel and Schedule. This allows the codegen to create navigation between these resources. ```rust ResourceIdentity::Teams => ResourceSettings::builder(path_name, ri) .imports(vec!["crate::users::*", "crate::teams::*"]) .api_client_links(vec![ ApiClientLinkSettings(Some("TeamsIdApiClient"), vec![ ApiClientLink::Struct("primary_channel", "PrimaryChannelApiClient"), ApiClientLink::Struct("schedule", "ScheduleApiClient"), ] ) ]).build().unwrap(), ``` -------------------------------- ### Get OneDrive Drive Item by ID using Graph RS SDK Source: https://context7.com/sreeise/graph-rs-sdk/llms.txt This snippet demonstrates how to retrieve a specific item from OneDrive by ID using the Graph RS SDK. It retrieves the drive item from the /me/drive/items/{item-id} endpoint and prints the response. ```rust use graph_rs_sdk::*; #[tokio::main] async fn main() -> GraphResult<()> { let client = GraphClient::new("ACCESS_TOKEN"); // Get item by ID let response = client .me() .drive() .item("ITEM_ID") .get_items() .send() .await?; println!("{:#?}", response); let body: serde_json::Value = response.json().await?; println!("{:#?}", body); Ok(()) } ``` -------------------------------- ### Async Client Usage in Rust Source: https://github.com/sreeise/graph-rs-sdk/blob/master/README.md Demonstrates how to instantiate and use the asynchronous GraphClient to make requests. It shows sending a request to list users and processing the JSON response. Requires the 'tokio' runtime. ```rust use graph_rs_sdk::* #[tokio::main] async fn main() -> GraphResult<()> { let client = GraphClient::new("ACCESS_TOKEN"); let response = client .users() .list_user() .send() .await?; println!(ירת{:#?}", response); let body: serde_json::Value = response.json().await?; println!(ירת{:#?}", body); Ok(()) } ``` -------------------------------- ### OpenAPI Count Method Collision Example Source: https://github.com/sreeise/graph-rs-sdk/wiki/Path-Based-Clients Illustrates a common issue in OpenAPI configurations where multiple distinct API endpoints are assigned the same method name (e.g., 'count'). This can lead to compilation errors in generated code if not handled properly. ```yaml "/teams/sharedWithTeams/$count" "/teams/{team-id}/primaryChannel/tabs/$count" "/teams/{team-id}/allChannels/$count" "/teams/{team-id}/schedule/timesOff/$count" ``` -------------------------------- ### Get User by ID using Graph RS SDK Source: https://context7.com/sreeise/graph-rs-sdk/llms.txt This snippet shows how to retrieve a specific user by their ID using the Graph RS SDK. It initializes the Graph client and sends a request to the /users/{user-id} endpoint. The response containing the user's information is then printed. ```rust use graph_rs_sdk::*; #[tokio::main] async fn main() -> GraphResult<()> { let client = GraphClient::new("ACCESS_TOKEN"); // Get specific user by ID let response = client .user("USER_ID") .get_user() .send() .await?; println!("{:#?}", response); let body: serde_json::Value = response.json().await?; println!("{:#?}", body); Ok(()) } ``` -------------------------------- ### Build Graph Client with Authorization Code Grant (Rust) Source: https://github.com/sreeise/graph-rs-sdk/wiki/Identity-Platform-SDK-User-Guide-Pre‐Release-Only Shows how to build a GraphClient using the Authorization Code Grant flow. This involves creating a ConfidentialClientApplication with an authorization code, client secret, redirect URI, and scopes. The client automatically handles token requests on the first API call. ```rust use graph_rs_sdk::{ Graph, oauth::ConfidentialClientApplication, }; async fn build_client( authorization_code: &str, client_id: &str, client_secret: &str, redirect_uri: url::Url, scope: Vec<&str> ) -> anyhow::Result { let mut confidential_client = ConfidentialClientApplication::builder(client_id) .with_authorization_code(authorization_code) // returns builder type for AuthorizationCodeCredential .with_client_secret(client_secret) .with_scope(scope) .with_redirect_uri(redirect_uri) .build(); let graph_client = Graph::from(confidential_client); Ok(graph_client) } ``` -------------------------------- ### Build GraphClient with Authorization Code Grant (Rust) Source: https://github.com/sreeise/graph-rs-sdk/blob/master/examples/identity_platform_auth/README.md Constructs a GraphClient using the Authorization Code Grant flow. This method is suitable for confidential clients and requires an authorization code obtained after user sign-in. Dependencies include `graph_rs_sdk` and `anyhow` for error handling. Inputs are authorization code, client ID, client secret, redirect URI, and scopes. ```rust use graph_rs_sdk::{ GraphClient, oauth::ConfidentialClientApplication, }; async fn build_client( authorization_code: &str, client_id: &str, client_secret: &str, redirect_uri: &str, scope: Vec<&str> ) -> anyhow::Result { let mut confidential_client = ConfidentialClientApplication::builder(client_id) .with_authorization_code(authorization_code) // returns builder type for AuthorizationCodeCredential .with_client_secret(client_secret) .with_scope(scope) .with_redirect_uri(redirect_uri)? .build(); let graph_client = GraphClient::from(confidential_client); Ok(graph_client) } ``` -------------------------------- ### Authenticate with Client Credentials Flow (Rust) Source: https://context7.com/sreeise/graph-rs-sdk/llms.txt Illustrates server-to-server authentication using the client credentials flow. This method is suitable for applications running as a service without user interaction. It involves building a `ConfidentialClientApplication` and using it to create a `GraphClient` that automatically handles token refresh. ```rust use graph_rs_sdk::{identity::ConfidentialClientApplication, GraphClient}; fn build_client(client_id: &str, client_secret: &str, tenant: &str) -> GraphClient { // Build confidential client with client credentials let mut confidential_client_application = ConfidentialClientApplication::builder(client_id) .with_client_secret(client_secret) .with_tenant(tenant) .build(); // Graph client will handle token refresh automatically GraphClient::from(&confidential_client_application) } #[tokio::main] async fn main() -> anyhow::Result<()> { let client = build_client("CLIENT_ID", "CLIENT_SECRET", "TENANT_ID"); // Now make API calls - tokens are managed automatically let response = client.users().list_user().send().await?; println!("{:#?}", response); Ok(()) } ``` -------------------------------- ### Generate Authorization URL with PKCE (Rust) Source: https://github.com/sreeise/graph-rs-sdk/blob/master/examples/authorization_sign_in/README.md Generates an authorization URL for the Authorization Code Grant flow incorporating Proof Key for Code Exchange (PKCE). PKCE enhances security by preventing authorization code interception. It requires client ID, redirect URI, scopes, and a generated PKCE verifier. ```rust use graph_rs_sdk::oauth::{AuthorizationCodeCredential, ProofKeyForCodeExchange}; fn auth_code_pkce_authorization_url(client_id: &str, redirect_uri: &str, scope: Vec) { let pkce = ProofKeyForCodeExchange::generate().unwrap(); let url = AuthorizationCodeCredential::authorization_url_builder(client_id) .with_redirect_uri(redirect_uri) .with_scope(scope) .with_pkce(&pkce) .url() .unwrap(); } ``` -------------------------------- ### Blocking Client Usage in Rust Source: https://github.com/sreeise/graph-rs-sdk/blob/master/README.md Illustrates the usage of the blocking GraphClient by converting an async client to a blocking one using `into_blocking()`. This example shows making a blocking request to list users and processing the JSON response. It does not require 'tokio'. ```rust use graph_rs_sdk::* fn main() -> GraphResult<()> { let client = GraphClient::new("ACCESS_TOKEN"); let response = client .users() .list_user() .into_blocking() .send()?; println!(ירת{:#?}", response); let body: serde_json::Value = response.json()?; println!(ירת{:#?}", body); Ok(()) } ``` -------------------------------- ### Create New Folder in OneDrive using Graph RS SDK Source: https://github.com/sreeise/graph-rs-sdk/blob/master/README.md This function demonstrates how to create a new folder in OneDrive using the Graph RS SDK. It initializes a GraphClient, defines a HashMap for the folder properties, and uses the create_children method to create the folder under a specified parent ID. ```rust use graph_rs_sdk::*; use std::collections::HashMap; static ACCESS_TOKEN: &str = "ACCESS_TOKEN"; static FOLDER_NAME: &str = "NEW_FOLDER_NAME"; static PARENT_ID: &str = "PARENT_ID"; // For more info on creating a folder see: // https://docs.microsoft.com/en-us/onedrive/developer/rest-api/api/driveitem_post_children?view=odsp-graph-online pub async fn create_new_folder() -> GraphResult<()> { let client = GraphClient::new(ACCESS_TOKEN); let folder: HashMap = HashMap::new(); let response = client .me() .drive() .item(PARENT_ID) .create_children(&serde_json::json!({ "name": FOLDER_NAME, "folder": folder, "@microsoft.graph.conflictBehavior": "fail" })) .send() .await?; println!("{:#?}", response); Ok(()) } ``` -------------------------------- ### Interactive Authentication with Graph SDK (Rust) Source: https://github.com/sreeise/graph-rs-sdk/wiki/Identity-Platform-SDK-User-Guide-Pre‐Release-Only This function demonstrates interactive authentication using the `graph-rs-sdk` and the `interactive-auth` feature, which utilizes the `wry` crate for web views. It requires specifying the tenant ID, client ID, client secret, redirect URI, and scopes. The `offline_access` scope is crucial for obtaining a refresh token. ```rust use graph_rs_sdk::{identity::{AuthorizationCodeCredential, Secret}, GraphClient}; async fn authenticate( tenant_id: &str, client_id: &str, client_secret: &str, redirect_uri: url::Url, scope: Vec<&str>, ) -> anyhow::Result { std::env::set_var("RUST_LOG", "debug"); pretty_env_logger::init(); let (authorization_query_response, mut credential_builder) = AuthorizationCodeCredential::authorization_url_builder(client_id) .with_tenant(tenant_id) .with_scope(scope) // Adds offline_access as a scope which is needed to get a refresh token. .with_redirect_uri(redirect_uri) .with_interactive_auth(Secret("client-secret".to_string()), Default::default()) .unwrap(); debug!("{authorization_query_response:#?}"); let mut confidential_client = credential_builder.with_client_secret(client_secret).build(); Ok(GraphClient::from(&confidential_client)) } ``` -------------------------------- ### Handle and Extract Error Messages from Graph API Responses in Rust Source: https://context7.com/sreeise/graph-rs-sdk/llms.txt This example shows how to handle and extract error messages from Microsoft Graph API responses. It uses `graph_rs_sdk`, `tokio`, and `std::error::Error`. The input is an access token and a request that may fail, with the output being either a success or a detailed Graph API error message. ```rust use graph_rs_sdk::{ http::ResponseExt, GraphClient }; use std::error::Error; #[tokio::main] async fn main() -> Result<(), Box> { let client = GraphClient::new("ACCESS_TOKEN"); let response = client.users().list_user().send().await?; // Check response status and extract error if present if !response.status().is_success() { if let Ok(error) = response.into_graph_error_message().await { println!("Graph API Error: {:#?}", error); return Err(Box::new(std::io::Error::new( std::io::ErrorKind::Other, format!("{:?}", error) ))); } } Ok(()) } ``` -------------------------------- ### List All Users using Graph RS SDK Source: https://context7.com/sreeise/graph-rs-sdk/llms.txt This snippet demonstrates how to retrieve a list of all users from Azure Active Directory using the Graph RS SDK. It initializes the Graph client and then sends a request to the /users endpoint. The response is then printed to the console. ```rust use graph_rs_sdk::*; #[tokio::main] async fn main() -> GraphResult<()> { let client = GraphClient::new("ACCESS_TOKEN"); // List all users let response = client .users() .list_user() .send() .await?; println!("{:#?}", response); let body: serde_json::Value = response.json().await?; println!("{:#?}", body); Ok(()) } ``` -------------------------------- ### Get Mail Folder using Graph RS SDK Source: https://github.com/sreeise/graph-rs-sdk/blob/master/README.md This function illustrates how to retrieve a specific mail folder using the Graph RS SDK. It initializes a GraphClient and employs the mail_folder method to target a mail folder by its ID, fetches the mail folder's details, and prints the response and body. ```rust use graph_rs_sdk::*; static ACCESS_TOKEN: &str = "ACCESS_TOKEN"; async fn get_mail_folder() -> GraphResult<()> { let client = GraphClient::new(ACCESS_TOKEN); let response = client.me() .mail_folder(MAIL_FOLDER_ID) .get_mail_folders() .send() .await?; println!("{:#?}", response); let body: serde_json::Value = response.json().await.unwrap(); println!("{:#?}", body); Ok(()) } ``` -------------------------------- ### Link ApiClients Macro Source: https://github.com/sreeise/graph-rs-sdk/wiki/Macro-Wiki The `api_client_link!` macro creates a method that facilitates transitioning between ApiClient instances. It transfers control and appends any known path parameters to the URL, enabling chained API calls. ```rust api_client_link!(calendar_views, CalendarViewApiClient); ``` -------------------------------- ### Get Item by Path in OneDrive using Graph RS SDK Source: https://github.com/sreeise/graph-rs-sdk/blob/master/README.md This function shows how to retrieve an item in OneDrive using its path with the Graph RS SDK. It initializes a GraphClient and utilizes the item_by_path method to specify the item's location, retrieves the item's information, and prints the response and body. ```rust // Pass the path location of the item staring from the OneDrive root folder. // Start the path with :/ and end with : async fn get_item_by_path() -> GraphResult<()> { let client = GraphClient::new("ACCESS_TOKEN"); let response = client .me() .drive() .item_by_path(":/documents/document.docx:") .get_items() .send() .await?; println!("{:#?}", response); let body: serde_json::Value = response.json().await?; println!("{:#?}", body); Ok(()) } ``` -------------------------------- ### Client Secret Credential for Graph Client (Rust) Source: https://github.com/sreeise/graph-rs-sdk/wiki/Identity-Platform-SDK-User-Guide-Pre‐Release-Only Illustrates how to obtain a Graph client using the client credentials grant flow with a client secret. This is suitable for server-to-server interactions. It requires the client ID and client secret. Dependencies include graph_rs_sdk. ```rust use graph_rs_sdk::{ oauth::ConfidentialClientApplication, Graph }; pub async fn get_graph_client(tenant: &str, client_id: &str, client_secret: &str) -> Graph { let mut confidential_client_application = ConfidentialClientApplication::builder(client_id) .with_client_secret(client_secret) .with_tenant(tenant) .build(); Graph::from(&confidential_client_application) } ``` -------------------------------- ### Upload Files to OneDrive using different methods in Rust Source: https://github.com/sreeise/graph-rs-sdk/blob/master/README.md This snippet shows different ways to upload files to OneDrive using the graph-rs-sdk. It uses std::fs::File and tokio::fs::File directly, as well as reqwest::Body for file uploads. The code depends on the graph-rs-sdk and tokio crates and includes both synchronous and asynchronous examples. ```rust use graph_rs_sdk::GraphClient; fn use_file_directly(file: File) -> anyhow::Result<()> { let client = GraphClient::new("token"); let _ = client .drive("drive-id") .item_by_path(":/drive/path:") .update_items_content(file) .into_blocking() .send()?; Ok(()) } async fn use_async_file_directly(file: tokio::fs::File) -> anyhow::Result<()> { let client = GraphClient::new("token"); let _ = client .drive("drive-id") .item_by_path(":/drive/path:") .update_items_content(file) .send() .await?; Ok(()) } ``` ```rust use graph_rs_sdk::GraphClient; use graph_rs_sdk::http::{Body, blocking}; fn use_reqwest_for_files(file: std::fs::File) -> anyhow::Result<()> { let client = GraphClient::new("token"); let _ = client.drive("drive-id") .item_by_path(":/drive/path:") .update_items_content(blocking::Body::from(file)) .into_blocking() .send()?; Ok(()) } async fn use_reqwest_for_async_files(file: tokio::fs::File) -> anyhow::Result<()> { let client = GraphClient::new("token"); let _ = client.drive("drive-id") .item_by_path(":/drive/path:") .update_items_content(Body::from(file)) .send() .await?; Ok(()) } ``` ```rust fn use_reqwest_for_files(file: File) -> anyhow::Result<()> { let client = GraphClient::new("token"); let _ = client .drive("drive-id") .item_by_path(":/drive/path:") .update_items_content(reqwest::blocking::Body::from(file)) .into_blocking() .send()?; Ok(()) } async fn use_reqwest_for_tokio_files(file: tokio::fs::File) -> anyhow::Result<()> { let client = GraphClient::new("token"); let _ = client .drive("drive-id") .item_by_path(":/drive/path:") .update_items_content(reqwest::Body::from(file)) .send() .await?; Ok(()) } ``` -------------------------------- ### Build GraphClient with OpenID Connect (Rust) Source: https://github.com/sreeise/graph-rs-sdk/blob/master/examples/identity_platform_auth/README.md Creates a GraphClient for OpenID Connect (OIDC) flows. OIDC extends OAuth 2.0 for authentication, enabling single sign-on via ID tokens. This function requires tenant ID, client ID, client secret, redirect URI, scopes, and an ID token. It utilizes `ConfidentialClientApplication` from the `graph_rs_sdk`. ```rust use graph_rs_sdk::{ GraphClient, oauth::ConfidentialClientApplication, }; fn build_client( tenant_id: &str, client_id: &str, client_secret: &str, redirect_uri: Url, scope: Vec<&str>, id_token: IdToken, ) -> GraphClient { let mut confidential_client = ConfidentialClientApplication::builder(client_id) .with_openid(id_token.code.unwrap(), client_secret) .with_tenant(tenant_id) .with_redirect_uri(redirect_uri) .with_scope(scope) .build(); GraphClient::from(&confidential_client) } ```