### Install Microsoft Graph SDK for Go Source: https://github.com/microsoftgraph/msgraph-sdk-go/blob/main/README.md Install the Microsoft Graph SDK for Go and the Azure identity authentication provider using go get. ```Shell go get github.com/microsoftgraph/msgraph-sdk-go go get github.com/microsoft/kiota-authentication-azure-go ``` -------------------------------- ### Create a New User Source: https://context7.com/microsoftgraph/msgraph-sdk-go/llms.txt Create a new user in the directory (POST /users). Requires accountEnabled, displayName, mailNickname, userPrincipalName, and passwordProfile. This example demonstrates setting a password profile with a forced change on next sign-in. ```go import ( "context" "fmt" "github.com/microsoftgraph/msgraph-sdk-go/models" ) password := models.NewPasswordProfile() pw := "P@ssw0rd123!" password.SetPassword(&pw) forceChange := true password.SetForceChangePasswordNextSignIn(&forceChange) newUser := models.NewUser() displayName := "Alice Contoso" mailNickname := "alice" upn := "alice@contoso.onmicrosoft.com" enabled := true newUser.SetDisplayName(&displayName) newUser.SetMailNickname(&mailNickname) newUser.SetUserPrincipalName(&upn) newUser.SetAccountEnabled(&enabled) newUser.SetPasswordProfile(password) created, err := client.Users().Post(context.Background(), newUser, nil) if err != nil { printOdataError(err) return } fmt.Printf("Created user: %s (id=%s)\n", *created.GetDisplayName(), *created.GetId()) // Output: Created user: Alice Contoso (id=) ``` -------------------------------- ### Get All Users in an Environment using Go Source: https://github.com/microsoftgraph/msgraph-sdk-go/blob/main/README.md Retrieves all users in an environment. Uses PageIterator for handling paginated results. Requires importing necessary Microsoft Graph SDK packages. ```Go import ( msgraphcore "github.com/microsoftgraph/msgraph-sdk-go-core" "github.com/microsoftgraph/msgraph-sdk-go/users" "github.com/microsoftgraph/msgraph-sdk-go/models" "github.com/microsoftgraph/msgraph-sdk-go/models/odataerrors" ) result, err := client.Users().Get(context.Background(), nil) if err != nil { fmt.Printf("Error getting users: %v\n", err) printOdataError(err) return err } // Use PageIterator to iterate through all users pageIterator, err := msgraphcore.NewPageIterator[models.Userable](result, client.GetAdapter(), models.CreateUserCollectionResponseFromDiscriminatorValue) err = pageIterator.Iterate(context.Background(), func(user models.Userable) bool { fmt.Printf("%s\n", *user.GetDisplayName()) // Return true to continue the iteration return true }) // omitted for brevity func printOdataError(err error) { switch err.(type) { case *odataerrors.ODataError: typed := err.(*odataerrors.ODataError) fmt.Printf("error: %s", typed.Error()) if terr := typed.GetErrorEscaped(); terr != nil { fmt.Printf("code: %s", *terr.GetCode()) fmt.Printf("msg: %s", *terr.GetMessage()) } default: fmt.Printf("%T > error: %#v", err, err) } } ``` -------------------------------- ### Get Signed-In User Profile with Select Source: https://context7.com/microsoftgraph/msgraph-sdk-go/llms.txt Retrieve the profile of the currently authenticated user using GET /me. Supports $select and $expand via query parameters to specify which fields to return. ```go import ( "context" "fmt" "github.com/microsoftgraph/msgraph-sdk-go/users" ) requestConfig := &users.UserItemRequestBuilderGetRequestConfiguration{ QueryParameters: &users.UserItemRequestBuilderGetQueryParameters{ Select: []string{"id", "displayName", "mail", "jobTitle", "officeLocation"}, }, } me, err := client.Me().Get(context.Background(), requestConfig) if err != nil { printOdataError(err) return } fmt.Printf("ID: %s\n", *me.GetId()) fmt.Printf("Name: %s\n", *me.GetDisplayName()) fmt.Printf("Mail: %s\n", *me.GetMail()) fmt.Printf("Title: %s\n", *me.GetJobTitle()) fmt.Printf("Location: %s\n", *me.GetOfficeLocation()) ``` -------------------------------- ### List Users with Filter, Top, Select, and Orderby Source: https://context7.com/microsoftgraph/msgraph-sdk-go/llms.txt List all users in the organization with optional OData filtering, ordering, and field selection. This example filters for enabled accounts, limits the results to 25, selects specific fields, and orders by display name. ```go import ( "context" "fmt" "github.com/microsoftgraph/msgraph-sdk-go/users" ) filter := "accountEnabled eq true" top := int32(25) result, err := client.Users().Get(context.Background(), &users.UsersRequestBuilderGetRequestConfiguration{ QueryParameters: &users.UsersRequestBuilderGetQueryParameters{ Filter: &filter, Top: &top, Select: []string{"id", "displayName", "mail", "userPrincipalName"}, Orderby: []string{"displayName asc"}, }, }) if err != nil { printOdataError(err) return } for _, u := range result.GetValue() { fmt.Printf("%s — %s\n", *u.GetDisplayName(), *u.GetMail()) } // Output: // Ada Lovelace — ada@contoso.com // Bob Smith — bob@contoso.com ``` -------------------------------- ### Get Signed-In User's OneDrive Source: https://context7.com/microsoftgraph/msgraph-sdk-go/llms.txt Retrieve the signed-in user's default OneDrive using GET /me/drive. This example shows how to fetch the drive ID and type. ```go import ( "context" "fmt" ) drive, err := client.Me().Drive().Get(context.Background(), nil) if err != nil { printOdataError(err) return } fmt.Printf("Drive ID: %s\n", *drive.GetId()) fmt.Printf("Drive type: %s\n", *drive.GetDriveType()) // Output: // Drive ID: b!aB3... // Drive type: personal ``` -------------------------------- ### Construct GraphRequestAdapter with Custom HTTP Client Source: https://context7.com/microsoftgraph/msgraph-sdk-go/llms.txt Create a GraphRequestAdapter when you need to supply a custom http.Client, parse-node factory, or serialization-writer factory. This example shows how to set a custom HTTP client with a 30-second timeout. ```go import ( nethttp "net/http" "time" absauth "github.com/microsoft/kiota-abstractions-go/authentication" msgraphsdk "github.com/microsoftgraph/msgraph-sdk-go" az "github.com/microsoftgraph/msgraph-sdk-go-core/authentication" azidentity "github.com/Azure/azure-sdk-for-go/sdk/azidentity" ) cred, _ := azidentity.NewClientSecretCredential("", "", "", nil) authProvider, _ := az.NewAzureIdentityAuthenticationProviderWithScopesAndValidHosts( cred, []string{"https://graph.microsoft.com/.default"}, []string{"graph.microsoft.com"}, ) // Custom HTTP client with a 30-second timeout. httpClient := &nethttp.Client{Timeout: 30 * time.Second} adapter, err := msgraphsdk.NewGraphRequestAdapterWithParseNodeFactoryAndSerializationWriterFactoryAndHttpClient( authProvider, nil, nil, httpClient, ) if err != nil { panic(err) } client := msgraphsdk.NewGraphServiceClient(adapter) ``` -------------------------------- ### Look up user by UPN directly on the client Source: https://context7.com/microsoftgraph/msgraph-sdk-go/llms.txt This example demonstrates an alternative method to retrieve a user by their User Principal Name (UPN) directly from the client, bypassing the standard `Users()` builder. ```APIDOC ## `client.UsersWithUserPrincipalName()` — Look up user by UPN directly on the client Provides an alternative path to retrieve a user via their User Principal Name without going through the `Users()` builder. ```go upn := "alice@contoso.com" user, err := client.UsersWithUserPrincipalName(&upn).Get(context.Background(), nil) if err != nil { printOdataError(err) return } fmt.Printf("Found: %s (id=%s)\n", *user.GetDisplayName(), *user.GetId()) ``` ``` -------------------------------- ### OData query parameters for collection requests Source: https://context7.com/microsoftgraph/msgraph-sdk-go/llms.txt This example demonstrates how to use OData system query options like `$filter`, `$select`, `$expand`, `$orderby`, and `$top` to refine collection requests. It shows how to construct a query to retrieve a specific user with expanded manager details and selected fields. ```APIDOC ## OData query parameters — `$filter`, `$select`, `$expand`, `$orderby`, `$top` Every collection request builder exposes a typed `QueryParameters` struct that maps to OData system query options, eliminating manual URL construction. ```go import ( "context" "fmt" "github.com/microsoftgraph/msgraph-sdk-go/users" ) // Get a specific user with expanded manager and selected fields. expand := []string{"manager($select=displayName,mail)"} selectFields := []string{"id", "displayName", "department", "manager"} user, err := client.Users().ByUserId("alice@contoso.com").Get( context.Background(), &users.UserItemRequestBuilderGetRequestConfiguration{ QueryParameters: &users.UserItemRequestBuilderGetQueryParameters{ Select: selectFields, Expand: expand, }, }, ) if err != nil { printOdataError(err) return } fmt.Printf("User: %s, Dept: %s\n", *user.GetDisplayName(), *user.GetDepartment()) if mgr := user.GetManager(); mgr != nil { // manager is returned as DirectoryObjectable; type-assert to Userable for full properties. fmt.Printf("Manager ODataType: %s\n", *mgr.GetOdataType()) } ``` ``` -------------------------------- ### List Groups with Filter Source: https://context7.com/microsoftgraph/msgraph-sdk-go/llms.txt Retrieves all groups in the organization, with an option to filter by type or properties. Example shows filtering for Microsoft 365 groups. ```go import ( "context" "fmt" "github.com/microsoftgraph/msgraph-sdk-go/groups" ) filter := "groupTypes/any(c:c eq 'Unified')" // Microsoft 365 groups only result, err := client.Groups().Get(context.Background(), &groups.GroupsRequestBuilderGetRequestConfiguration{ QueryParameters: &groups.GroupsRequestBuilderGetQueryParameters{ Filter: &filter, Select: []string{"id", "displayName", "mail", "membershipRule"}, }, }) if err != nil { printOdataError(err) return } for _, g := range result.GetValue() { fmt.Printf("%s — %s\n", *g.GetId(), *g.GetDisplayName()) } ``` -------------------------------- ### Create a change-notification webhook Source: https://context7.com/microsoftgraph/msgraph-sdk-go/llms.txt This example shows how to create a webhook subscription to receive change notifications from Microsoft Graph. It demonstrates setting the resource, change type, notification URL, client state, and expiration time. ```APIDOC ## `client.Subscriptions().Post()` — Create a change-notification webhook Creates a webhook subscription for Graph change notifications (`POST /subscriptions`). When resources change, Graph posts a notification to the supplied `notificationUrl`. ```go import ( "context" "fmt" "time" "github.com/microsoftgraph/msgraph-sdk-go/models" ) sub := models.NewSubscription() resource := "me/mailFolders('Inbox')/messages" changeType := "created,updated" notifURL := "https://webhook.contoso.com/api/notifications" clientState := "secretClientState" expiry := time.Now().UTC().Add(4230 * time.Minute) // max ~3 days for messages expiryStr := expiry.Format(time.RFC3339) sub.SetResource(&resource) sub.SetChangeType(&changeType) sub.SetNotificationUrl(¬ifURL) sub.SetClientState(&clientState) sub.SetExpirationDateTime(&expiry) created, err := client.Subscriptions().Post(context.Background(), sub, nil) if err != nil { printOdataError(err) return } fmt.Printf("Subscription created: %s (expires %s)\n", *created.GetId(), created.GetExpirationDateTime().Format(time.RFC3339)) ``` ``` -------------------------------- ### Get User's Drive Information Source: https://github.com/microsoftgraph/msgraph-sdk-go/blob/main/README.md Retrieve the current user's drive information using the GraphServiceClient. Includes a helper function to print OData errors. ```Golang import ( "github.com/microsoftgraph/msgraph-sdk-go/models/odataerrors" ) result, err := client.Me().Drive().Get(context.Background(), nil) if err != nil { fmt.Printf("Error getting the drive: %v\n", err) printOdataError(err) } fmt.Printf("Found Drive : %v\n", *result.GetId()) // omitted for brevity func printOdataError(err error) { switch err.(type) { case *odataerrors.ODataError: typed := err.(*odataerrors.ODataError) fmt.Printf("error:", typed.Error()) if terr := typed.GetErrorEscaped(); terr != nil { fmt.Printf("code: %s", *terr.GetCode()) fmt.Printf("msg: %s", *terr.GetMessage()) } default: fmt.Printf("%T > error: %#v", err, err) } } ``` -------------------------------- ### Structured error handling with ODataError Source: https://context7.com/microsoftgraph/msgraph-sdk-go/llms.txt This example illustrates how to handle errors returned by Microsoft Graph API requests. It shows how to check for a typed `*odataerrors.ODataError` and extract details such as the error code, message, and request ID. ```APIDOC ## `ODataError` — Structured error handling All request methods return a typed `*odataerrors.ODataError` on 4xx/5xx responses, which carries the OData error code, message, and optional inner errors. ```go import ( "errors" "github.com/microsoftgraph/msgraph-sdk-go/models/odataerrors" ) _, err := client.Users().ByUserId("nonexistent-id").Get(context.Background(), nil) if err != nil { var odataErr *odataerrors.ODataError if errors.As(err, &odataErr) { mainErr := odataErr.GetErrorEscaped() fmt.Printf("Graph API error\n") fmt.Printf(" Code: %s\n", *mainErr.GetCode()) fmt.Printf(" Message: %s\n", *mainErr.GetMessage()) // Inner errors may contain more detail. if inner := mainErr.GetInnerError(); inner != nil { fmt.Printf(" Request-id: %s\n", *inner.GetRequestId()) } } else { fmt.Printf("Non-Graph error: %v\n", err) } } // Output: // Code: Request_ResourceNotFound // Message: Resource 'nonexistent-id' does not exist ... ``` ``` -------------------------------- ### client.Users().Post() Source: https://context7.com/microsoftgraph/msgraph-sdk-go/llms.txt Creates a new user in the directory. Requires at minimum `accountEnabled`, `displayName`, `mailNickname`, `userPrincipalName`, and `passwordProfile`. ```APIDOC ## `client.Users().Post()` — Create a user Creates a new user in the directory (`POST /users`). Requires at minimum `accountEnabled`, `displayName`, `mailNickname`, `userPrincipalName`, and `passwordProfile`. ```go import ( "context" "fmt" "github.com/microsoftgraph/msgraph-sdk-go/models" ) password := models.NewPasswordProfile() pw := "P@ssw0rd123!" password.SetPassword(&pw) forceChange := true password.SetForceChangePasswordNextSignIn(&forceChange) newUser := models.NewUser() displayName := "Alice Contoso" mailNickname := "alice" upn := "alice@contoso.onmicrosoft.com" enabled := true newUser.SetDisplayName(&displayName) newUser.SetMailNickname(&mailNickname) newUser.SetUserPrincipalName(&upn) newUser.SetAccountEnabled(&enabled) newUser.SetPasswordProfile(password) created, err := client.Users().Post(context.Background(), newUser, nil) if err != nil { printOdataError(err) return } fmt.Printf("Created user: %s (id=%s)\n", *created.GetDisplayName(), *created.GetId()) // Output: Created user: Alice Contoso (id=) ``` ``` -------------------------------- ### Create GraphServiceClient with Credentials Source: https://github.com/microsoftgraph/msgraph-sdk-go/blob/main/README.md Instantiate a GraphServiceClient using the provided credentials and requested scopes to make authenticated requests to Microsoft Graph. ```Golang import msgraphsdk "github.com/microsoftgraph/msgraph-sdk-go" client , err := msgraphsdk.NewGraphServiceClientWithCredentials(cred, []string{"Files.Read"}) if err != nil { fmt.Printf("Error creating client: %v\n", err) return } ``` -------------------------------- ### Create GraphServiceClient with Custom Hosts for National Clouds Source: https://context7.com/microsoftgraph/msgraph-sdk-go/llms.txt Instantiate a GraphServiceClient with explicit allowed hostnames, suitable for national cloud deployments. Optionally, override the base URL on the adapter for specific endpoints. ```go cred, _ := azidentity.NewClientSecretCredential("", "", "", nil) // Target the US Government GCC High endpoint. client, err := msgraphsdk.NewGraphServiceClientWithCredentialsAndHosts( cred, []string{"https://graph.microsoft.us/.default"}, []string{"graph.microsoft.us"}, ) if err != nil { panic(err) } // Optionally override the base URL on the adapter. client.GetAdapter().SetBaseUrl("https://graph.microsoft.us/v1.0") ``` -------------------------------- ### Create Authenticated GraphServiceClient with ClientSecretCredential Source: https://context7.com/microsoftgraph/msgraph-sdk-go/llms.txt Instantiate a GraphServiceClient using ClientSecretCredential for daemon or service applications. This automatically configures the request adapter, default scopes, and Graph endpoints. It verifies the client by fetching the signed-in user's information. ```go package main import ( "context" "fmt" azidentity "github.com/Azure/azure-sdk-for-go/sdk/azidentity" msgraphsdk "github.com/microsoftgraph/msgraph-sdk-go" "github.com/microsoftgraph/msgraph-sdk-go/models/odataerrors" ) func main() { // ClientSecretCredential is suitable for daemon / service apps. cred, err := azidentity.NewClientSecretCredential( "", "", "", nil, ) if err != nil { panic(fmt.Sprintf("error creating credential: %v", err)) } client, err := msgraphsdk.NewGraphServiceClientWithCredentials( cred, []string{"https://graph.microsoft.com/.default"}, ) if err != nil { panic(fmt.Sprintf("error creating client: %v", err)) } // Verify the client works by fetching the signed-in user. me, err := client.Me().Get(context.Background(), nil) if err != nil { printOdataError(err) return } fmt.Printf("Signed in as: %s <%s>\n", *me.GetDisplayName(), *me.GetMail()) } func printOdataError(err error) { switch typed := err.(type) { case *odataerrors.ODataError: fmt.Printf("ODataError: %s\n", typed.Error()) if e := typed.GetErrorEscaped(); e != nil { fmt.Printf(" code: %s\n", *e.GetCode()) fmt.Printf(" message: %s\n", *e.GetMessage()) } default: fmt.Printf("%T: %v\n", err, err) } } ``` -------------------------------- ### client.Me().Drive().Get() Source: https://context7.com/microsoftgraph/msgraph-sdk-go/llms.txt Retrieves the user's default OneDrive. ```APIDOC ## `client.Me().Drive().Get()` — Get the signed-in user's OneDrive Retrieves the user's default OneDrive (`GET /me/drive`). ```go import ( "context" "fmt" ) drive, err := client.Me().Drive().Get(context.Background(), nil) if err != nil { printOdataError(err) return } fmt.Printf("Drive ID: %s\n", *drive.GetId()) fmt.Printf("Drive type: %s\n", *drive.GetDriveType()) // Output: // Drive ID: b!aB3... // Drive type: personal ``` ``` -------------------------------- ### Look up user by UPN using client.UsersWithUserPrincipalName() Source: https://context7.com/microsoftgraph/msgraph-sdk-go/llms.txt This method provides a direct way to retrieve a user by their User Principal Name (UPN) from the client, bypassing the standard `Users()` builder. This is useful for quick lookups when the UPN is known. ```go upn := "alice@contoso.com" user, err := client.UsersWithUserPrincipalName(&upn).Get(context.Background(), nil) if err != nil { printOdataError(err) return } fmt.Printf("Found: %s (id=%s)\n", *user.GetDisplayName(), *user.GetId()) ``` -------------------------------- ### Query users with OData parameters like $filter, $select, $expand Source: https://context7.com/microsoftgraph/msgraph-sdk-go/llms.txt Leverage the typed `QueryParameters` struct to construct OData queries for collection requests. This eliminates manual URL construction and ensures type safety. Use `$select` to specify fields and `$expand` to include related resources. ```go import ( "context" "fmt" "github.com/microsoftgraph/msgraph-sdk-go/users" ) // Get a specific user with expanded manager and selected fields. expand := []string{"manager($select=displayName,mail)"} selectFields := []string{"id", "displayName", "department", "manager"} user, err := client.Users().ByUserId("alice@contoso.com").Get( context.Background(), &users.UserItemRequestBuilderGetRequestConfiguration{ QueryParameters: &users.UserItemRequestBuilderGetQueryParameters{ Select: selectFields, Expand: expand, }, }, ) if err != nil { printOdataError(err) return } fmt.Printf("User: %s, Dept: %s\n", *user.GetDisplayName(), *user.GetDepartment()) if mgr := user.GetManager(); mgr != nil { // manager is returned as DirectoryObjectable; type-assert to Userable for full properties. fmt.Printf("Manager ODataType: %s\n", *mgr.GetOdataType()) } ``` -------------------------------- ### NewGraphServiceClientWithCredentialsAndHosts Source: https://context7.com/microsoftgraph/msgraph-sdk-go/llms.txt Same as above but accepts an explicit list of allowed Graph endpoint hostnames, useful for national clouds (GCC High, DoD, Germany, China). ```APIDOC ## NewGraphServiceClientWithCredentialsAndHosts ### Description Same as `NewGraphServiceClientWithCredentials` but accepts an explicit list of allowed Graph endpoint hostnames, useful for national clouds (GCC High, DoD, Germany, China). ### Method Signature `NewGraphServiceClientWithCredentialsAndHosts(credential azcore.TokenCredential, scopes []string, hosts []string) (*GraphServiceClient, error)` ### Parameters * `credential` (azcore.TokenCredential) - The authentication credential. * `scopes` ([]string) - The scopes to request. * `hosts` ([]string) - A list of allowed Graph endpoint hostnames. ### Returns * `*GraphServiceClient` - An authenticated GraphServiceClient. * `error` - An error if the client creation fails. ### Example ```go cred, _ := azidentity.NewClientSecretCredential("", "", "", nil) // Target the US Government GCC High endpoint. client, err := msgraphsdk.NewGraphServiceClientWithCredentialsAndHosts( cred, []string{"https://graph.microsoft.us/.default"}, []string{"graph.microsoft.us"}, ) if err != nil { panic(err) } // Optionally override the base URL on the adapter. client.GetAdapter().SetBaseUrl("https://graph.microsoft.us/v1.0") ``` ``` -------------------------------- ### client.Me().Get() Source: https://context7.com/microsoftgraph/msgraph-sdk-go/llms.txt Retrieves the profile of the currently authenticated user. Supports `$select` and `$expand` query parameters. ```APIDOC ## `client.Me().Get()` — Get the signed-in user profile Retrieves the profile of the currently authenticated user (`GET /me`). Supports `$select` and `$expand` via query parameters. ```go import ( "context" "fmt" "github.com/microsoftgraph/msgraph-sdk-go/users" ) requestConfig := &users.UserItemRequestBuilderGetRequestConfiguration{ QueryParameters: &users.UserItemRequestBuilderGetQueryParameters{ Select: []string{"id", "displayName", "mail", "jobTitle", "officeLocation"}, }, } me, err := client.Me().Get(context.Background(), requestConfig) if err != nil { printOdataError(err) return } fmt.Printf("ID: %s\n", *me.GetId()) fmt.Printf("Name: %s\n", *me.GetDisplayName()) fmt.Printf("Mail: %s\n", *me.GetMail()) fmt.Printf("Title: %s\n", *me.GetJobTitle()) fmt.Printf("Location: %s\n", *me.GetOfficeLocation()) ``` ``` -------------------------------- ### List Mail Messages with OData Options Source: https://context7.com/microsoftgraph/msgraph-sdk-go/llms.txt Retrieves messages from the signed-in user's mailbox. Supports OData query parameters like Top, Select, and Orderby. ```go import ( "context" "fmt" "github.com/microsoftgraph/msgraph-sdk-go/users" ) top := int32(10) result, err := client.Me().Messages().Get(context.Background(), &users.ItemMessagesRequestBuilderGetRequestConfiguration{ QueryParameters: &users.ItemMessagesRequestBuilderGetQueryParameters{ Top: &top, Select: []string{"subject", "from", "receivedDateTime", "isRead"}, Orderby: []string{"receivedDateTime desc"}, }, }) if err != nil { printOdataError(err) return } for _, msg := range result.GetValue() { status := "read" if !*msg.GetIsRead() { status = "UNREAD" } fmt.Printf("[%s] %s — %s\n", status, *msg.GetSubject(), *msg.GetFrom().GetEmailAddress().GetAddress()) } ``` -------------------------------- ### NewGraphServiceClientWithCredentials Source: https://context7.com/microsoftgraph/msgraph-sdk-go/llms.txt Instantiates a GraphServiceClient directly from any azcore.TokenCredential. Automatically configures the request adapter, default scopes, and all valid Graph endpoints. ```APIDOC ## NewGraphServiceClientWithCredentials ### Description Instantiates a `GraphServiceClient` directly from any `azcore.TokenCredential`. Automatically configures the request adapter, default scopes, and all valid Graph endpoints. ### Method Signature `NewGraphServiceClientWithCredentials(credential azcore.TokenCredential, scopes []string) (*GraphServiceClient, error)` ### Parameters * `credential` (azcore.TokenCredential) - The authentication credential. * `scopes` ([]string) - The scopes to request. ### Returns * `*GraphServiceClient` - An authenticated GraphServiceClient. * `error` - An error if the client creation fails. ### Example ```go package main import ( "context" "fmt" azidentity "github.com/Azure/azure-sdk-for-go/sdk/azidentity" msgraphsdk "github.com/microsoftgraph/msgraph-sdk-go" "github.com/microsoftgraph/msgraph-sdk-go/models/odataerrors" ) func main() { // ClientSecretCredential is suitable for daemon / service apps. cred, err := azidentity.NewClientSecretCredential( "", "", "", nil, ) if err != nil { panic(fmt.Sprintf("error creating credential: %v", err)) } client, err := msgraphsdk.NewGraphServiceClientWithCredentials( cred, []string{"https://graph.microsoft.com/.default"}, ) if err != nil { panic(fmt.Sprintf("error creating client: %v", err)) } // Verify the client works by fetching the signed-in user. me, err := client.Me().Get(context.Background(), nil) if err != nil { printOdataError(err) return } fmt.Printf("Signed in as: %s <%s>\n", *me.GetDisplayName(), *me.GetMail()) } func printOdataError(err error) { switch typed := err.(type) { case *odataerrors.ODataError: fmt.Printf("ODataError: %s\n", typed.Error()) if e := typed.GetErrorEscaped(); e != nil { fmt.Printf(" code: %s\n", *e.GetCode()) fmt.Printf(" message: %s\n", *e.GetMessage()) } default: fmt.Printf("%T: %v\n", err, err) } } ``` ``` -------------------------------- ### client.Users().Get() Source: https://context7.com/microsoftgraph/msgraph-sdk-go/llms.txt Lists all users in the organization with optional OData filtering, ordering, and field selection. Returns a `UserCollectionResponseable`. ```APIDOC ## `client.Users().Get()` — List users Lists all users in the organization with optional OData filtering, ordering, and field selection. Returns a `UserCollectionResponseable`. ```go import ( "context" "fmt" "github.com/microsoftgraph/msgraph-sdk-go/users" ) filter := "accountEnabled eq true" top := int32(25) result, err := client.Users().Get(context.Background(), &users.UsersRequestBuilderGetRequestConfiguration{ QueryParameters: &users.UsersRequestBuilderGetQueryParameters{ Filter: &filter, Top: &top, Select: []string{"id", "displayName", "mail", "userPrincipalName"}, Orderby: []string{"displayName asc"}, }, }) if err != nil { printOdataError(err) return } for _, u := range result.GetValue() { fmt.Printf("%s — %s\n", *u.GetDisplayName(), *u.GetMail()) } // Output: // Ada Lovelace — ada@contoso.com // Bob Smith — bob@contoso.com ``` ``` -------------------------------- ### Create DeviceCodeCredential for Authentication Source: https://github.com/microsoftgraph/msgraph-sdk-go/blob/main/README.md Create a DeviceCodeCredential object for authenticating with Microsoft Graph using the device code flow. Ensure public client flows are enabled on your app registration. ```Golang import ( azidentity "github.com/Azure/azure-sdk-for-go/sdk/azidentity" "context" ) cred, err := azidentity.NewDeviceCodeCredential(&azidentity.DeviceCodeCredentialOptions{ TenantID: "", ClientID: "", UserPrompt: func(ctx context.Context, message azidentity.DeviceCodeMessage) error { fmt.Println(message.Message) return nil }, }) if err != nil { fmt.Printf("Error creating credentials: %v\n", err) } ``` -------------------------------- ### NewGraphRequestAdapter Source: https://context7.com/microsoftgraph/msgraph-sdk-go/llms.txt Creates a GraphRequestAdapter, allowing for custom HTTP clients and serialization factories. ```APIDOC ## `NewGraphRequestAdapter` — Low-level adapter construction Creates the `GraphRequestAdapter` separately when you need to supply a custom `http.Client`, a custom parse-node factory, or a custom serialization-writer factory. ```go import ( nethttp "net/http" "time" absauth "github.com/microsoft/kiota-abstractions-go/authentication" msgraphsdk "github.com/microsoftgraph/msgraph-sdk-go" az "github.com/microsoftgraph/msgraph-sdk-go-core/authentication" azidentity "github.com/Azure/azure-sdk-for-go/sdk/azidentity" ) cred, _ := azidentity.NewClientSecretCredential("", "", "", nil) authProvider, _ := az.NewAzureIdentityAuthenticationProviderWithScopesAndValidHosts( cred, []string{"https://graph.microsoft.com/.default"}, []string{"graph.microsoft.com"}, ) // Custom HTTP client with a 30-second timeout. httpClient := &nethttp.Client{Timeout: 30 * time.Second} adapter, err := msgraphsdk.NewGraphRequestAdapterWithParseNodeFactoryAndSerializationWriterFactoryAndHttpClient( authProvider, nil, nil, httpClient, ) if err != nil { panic(err) } client := msgraphsdk.NewGraphServiceClient(adapter) ``` ``` -------------------------------- ### Create a Group Source: https://context7.com/microsoftgraph/msgraph-sdk-go/llms.txt Creates a new group in Microsoft Graph. Set `GroupTypes` to `["Unified"]` for a Microsoft 365 group or leave empty for a security group. ```go import ( "context" "fmt" "github.com/microsoftgraph/msgraph-sdk-go/models" ) group := models.NewGroup() displayName := "Engineering All-Hands" mailNickname := "eng-allhands" mailEnabled := true securityEnabled := false group.SetDisplayName(&displayName) group.SetMailNickname(&mailNickname) group.SetMailEnabled(&mailEnabled) group.SetSecurityEnabled(&securityEnabled) group.SetGroupTypes([]string{"Unified"}) created, err := client.Groups().Post(context.Background(), group, nil) if err != nil { printOdataError(err) return } fmt.Printf("Created group: %s (id=%s)\n", *created.GetDisplayName(), *created.GetId()) ``` -------------------------------- ### Conventional Commit Message Format Source: https://github.com/microsoftgraph/msgraph-sdk-go/blob/main/CONTRIBUTING.md Follow this format for commit messages to support automated release processes. It includes a header with type and description, an optional body, and optional footers. ```text [optional scope]: ``` -------------------------------- ### Create a change-notification webhook using client.Subscriptions().Post() Source: https://context7.com/microsoftgraph/msgraph-sdk-go/llms.txt Use this snippet to create a webhook subscription for Graph change notifications. The Graph API will post notifications to the specified `notificationUrl` when resources change. Ensure the `notificationUrl` is publicly accessible. ```go import ( "context" "fmt" "time" "github.com/microsoftgraph/msgraph-sdk-go/models" ) sub := models.NewSubscription() resource := "me/mailFolders('Inbox')/messages" changeType := "created,updated" notifURL := "https://webhook.contoso.com/api/notifications" clientState := "secretClientState" expiry := time.Now().UTC().Add(4230 * time.Minute) // max ~3 days for messages expiryStr := expiry.Format(time.RFC3339) sub.SetResource(&resource) sub.SetChangeType(&changeType) sub.SetNotificationUrl(¬ifURL) sub.SetClientState(&clientState) sub.SetExpirationDateTime(&expiry) created, err := client.Subscriptions().Post(context.Background(), sub, nil) if err != nil { printOdataError(err) return } fmt.Printf("Subscription created: %s (expires %s)\n", *created.GetId(), created.GetExpirationDateTime().Format(time.RFC3339)) ``` -------------------------------- ### Create a Group Source: https://context7.com/microsoftgraph/msgraph-sdk-go/llms.txt Creates a new group in the organization. Can be a Microsoft 365 group or a security group. ```APIDOC ## `client.Groups().Post()` — Create a group ### Description Creates a new group (`POST /groups`). Set `GroupTypes` to `["Unified"]` for a Microsoft 365 group or leave empty for a security group. ### Method POST ### Endpoint /groups ### Parameters #### Request Body - **group** (Group) - Required - The properties of the group to create. - **displayName** (string) - Required - The display name for the group. - **mailNickname** (string) - Required - The mail alias for the group. - **mailEnabled** (boolean) - Required - Whether mail is enabled for the group. - **securityEnabled** (boolean) - Required - Whether the group is a security group. - **groupTypes** (array of string) - Optional - Specifies the type of group (e.g., `["Unified"]` for Microsoft 365 groups). ### Request Example ```go import ( "context" "fmt" "github.com/microsoftgraph/msgraph-sdk-go/models" ) group := models.NewGroup() displayName := "Engineering All-Hands" mailNickname := "eng-allhands" mailEnabled := true securityEnabled := false group.SetDisplayName(&displayName) group.SetMailNickname(&mailNickname) group.SetMailEnabled(&mailEnabled) group.SetSecurityEnabled(&securityEnabled) group.SetGroupTypes([]string{"Unified"}) created, err := client.Groups().Post(context.Background(), group, nil) if err != nil { printOdataError(err) return } fmt.Printf("Created group: %s (id=%s)\n", *created.GetDisplayName(), *created.GetId()) ``` ### Response #### Success Response (201) - **id** (string) - The unique identifier for the newly created group. - **displayName** (string) - The display name of the group. ``` -------------------------------- ### Access Specific User by ID or UPN Source: https://context7.com/microsoftgraph/msgraph-sdk-go/llms.txt Obtain a UserItemRequestBuilder scoped to a single user using their ID or User Principal Name (UPN). From this builder, you can access all per-user sub-resources like mail, calendar, and drive. ```go import "context" userId := "alice@contoso.onmicrosoft.com" // or object ID GUID user, err := client.Users().ByUserId(userId).Get(context.Background(), nil) if err != nil { printOdataError(err) return } fmt.Println(*user.GetDisplayName()) ``` -------------------------------- ### Send Email using Graph SDK for Go Source: https://context7.com/microsoftgraph/msgraph-sdk-go/llms.txt Sends an email on behalf of the authenticated user. The message is saved in Sent Items by default. ```go import ( "context" "fmt" "github.com/microsoftgraph/msgraph-sdk-go/models" "github.com/microsoftgraph/msgraph-sdk-go/users" ) toAddr := models.NewEmailAddress() addr := "bob@contoso.com" name := "Bob Smith" toAddr.SetAddress(&addr) toAddr.SetName(&name) recipient := models.NewRecipient() recipient.SetEmailAddress(toAddr) body := models.NewItemBody() bodyContent := "Hello Bob, this is a test message sent via the Graph SDK for Go." bodyType := models.TEXT_BODYTYPE body.SetContent(&bodyContent) body.SetContentType(&bodyType) message := models.NewMessage() subject := "Hello from Graph SDK for Go" message.SetSubject(&subject) message.SetBody(body) message.SetToRecipients([]models.Recipientable{recipient}) requestBody := users.NewItemSendMailPostRequestBody() saveToSentItems := true requestBody.SetMessage(message) requestBody.SetSaveToSentItems(&saveToSentItems) err := client.Me().SendMail().Post(context.Background(), requestBody, nil) if err != nil { printOdataError(err) return } fmt.Println("Email sent successfully.") ``` -------------------------------- ### Send an Email Source: https://context7.com/microsoftgraph/msgraph-sdk-go/llms.txt Sends an email on behalf of the authenticated user. The message is saved in the Sent Items folder by default. ```APIDOC ## `client.Me().SendMail()` — Send an email ### Description Sends an email on behalf of the authenticated user (`POST /me/sendMail`). The message is saved in Sent Items. ### Method POST ### Endpoint /me/sendMail ### Parameters #### Request Body - **message** (Message) - Required - The message to send. - **saveToSentItems** (boolean) - Optional - Whether to save the sent message to the Sent Items folder. ### Request Example ```go import ( "context" "fmt" "github.com/microsoftgraph/msgraph-sdk-go/models" "github.com/microsoftgraph/msgraph-sdk-go/users" ) toAddr := models.NewEmailAddress() addr := "bob@contoso.com" name := "Bob Smith" toAddr.SetAddress(&addr) toAddr.SetName(&name) recipient := models.NewRecipient() recipient.SetEmailAddress(toAddr) body := models.NewItemBody() bodyContent := "Hello Bob, this is a test message sent via the Graph SDK for Go." bodyType := models.TEXT_BODYTYPE body.SetContent(&bodyContent) body.SetContentType(&bodyType) message := models.NewMessage() subject := "Hello from Graph SDK for Go" message.SetSubject(&subject) message.SetBody(body) message.SetToRecipients([]models.Recipientable{recipient}) requestBody := users.NewItemSendMailPostRequestBody() saveToSentItems := true requestBody.SetMessage(message) requestBody.SetSaveToSentItems(&saveToSentItems) err := client.Me().SendMail().Post(context.Background(), requestBody, nil) if err != nil { printOdataError(err) return } fmt.Println("Email sent successfully.") ``` ### Response #### Success Response (204) No content is returned on successful send. ``` -------------------------------- ### client.Users().ByUserId() Source: https://context7.com/microsoftgraph/msgraph-sdk-go/llms.txt Accesses a specific user by ID or UPN, returning a `UserItemRequestBuilder` for further operations. ```APIDOC ## `client.Users().ByUserId()` — Access a specific user by ID or UPN Returns a `UserItemRequestBuilder` scoped to a single user, from which all per-user sub-resources (mail, calendar, drive, etc.) can be accessed. ```go import "context" userId := "alice@contoso.onmicrosoft.com" // or object ID GUID user, err := client.Users().ByUserId(userId).Get(context.Background(), nil) if err != nil { printOdataError(err) return } fmt.Println(*user.GetDisplayName()) ``` ``` -------------------------------- ### Iterate Over Paged Collections with PageIterator Source: https://context7.com/microsoftgraph/msgraph-sdk-go/llms.txt Uses `msgraphcore.NewPageIterator` to automatically handle OData `@odata.nextLink` tokens for iterating through large collections without manual paging. ```go import ( "context" "fmt" msgraphcore "github.com/microsoftgraph/msgraph-sdk-go-core" "github.com/microsoftgraph/msgraph-sdk-go/models" ) // First page — the iterator takes it from here. result, err := client.Users().Get(context.Background(), nil) if err != nil { printOdataError(err) return } pageIterator, err := msgraphcore.NewPageIterator[models.Userable]( result, client.GetAdapter(), models.CreateUserCollectionResponseFromDiscriminatorValue, ) if err != nil { panic(err) } var count int err = pageIterator.Iterate(context.Background(), func(user models.Userable) bool { count++ fmt.Printf("%d: %s\n", count, *user.GetDisplayName()) return true // return false to stop early }) if err != nil { printOdataError(err) } fmt.Printf("Total users: %d\n", count) ``` -------------------------------- ### List Groups Source: https://context7.com/microsoftgraph/msgraph-sdk-go/llms.txt Retrieves all groups in the organization. Supports filtering by type or properties. ```APIDOC ## `client.Groups().Get()` — List groups ### Description Retrieves all groups in the organization, optionally filtered by type or properties (`GET /groups`). ### Method GET ### Endpoint /groups ### Parameters #### Query Parameters - **filter** (string) - Optional - Filters the results based on OData filter expressions. - **select** (string array) - Optional - Specifies the properties to return for each group. ### Request Example ```go import ( "context" "fmt" "github.com/microsoftgraph/msgraph-sdk-go/groups" ) filter := "groupTypes/any(c:c eq 'Unified')" // Microsoft 365 groups only result, err := client.Groups().Get(context.Background(), &groups.GroupsRequestBuilderGetRequestConfiguration{ QueryParameters: &groups.GroupsRequestBuilderGetQueryParameters{ Filter: &filter, Select: []string{"id", "displayName", "mail", "membershipRule"}, }, }) if err != nil { printOdataError(err) return } for _, g := range result.GetValue() { fmt.Printf("%s — %s\n", *g.GetId(), *g.GetDisplayName()) } ``` ### Response #### Success Response (200) - **value** (array of Group) - A collection of groups. ``` -------------------------------- ### List Mail Messages Source: https://context7.com/microsoftgraph/msgraph-sdk-go/llms.txt Retrieves messages from the signed-in user's mailbox with full OData support. Supports filtering, selecting fields, and ordering. ```APIDOC ## `client.Me().Messages().Get()` — List mail messages ### Description Retrieves messages from the signed-in user's mailbox with full OData support (`GET /me/messages`). ### Method GET ### Endpoint /me/messages ### Parameters #### Query Parameters - **top** (int32) - Optional - The maximum number of messages to return. - **select** (string array) - Optional - Specifies the properties to return for each message. - **orderby** (string array) - Optional - Specifies the order in which to return messages. ### Request Example ```go import ( "context" "fmt" "github.com/microsoftgraph/msgraph-sdk-go/users" ) top := int32(10) result, err := client.Me().Messages().Get(context.Background(), &users.ItemMessagesRequestBuilderGetRequestConfiguration{ QueryParameters: &users.ItemMessagesRequestBuilderGetQueryParameters{ Top: &top, Select: []string{"subject", "from", "receivedDateTime", "isRead"}, Orderby: []string{"receivedDateTime desc"}, }, }) if err != nil { printOdataError(err) return } for _, msg := range result.GetValue() { status := "read" if !*msg.GetIsRead() { status = "UNREAD" } fmt.Printf("[%s] %s — %s\n", status, *msg.GetSubject(), *msg.GetFrom().GetEmailAddress().GetAddress()) } ``` ### Response #### Success Response (200) - **value** (array of Message) - A collection of messages. ```