Microsoft Graph SDK for Go

repository·main·Indexed 43 days ago

https://github.com/microsoftgraph/msgraph-sdk-go

A type-safe, fluent interface for interacting with the Microsoft Graph v1.0 API. This SDK allows Go developers to manage Microsoft 365 resources, including users, files, and drives, using the GraphServiceClient and GraphRequestAdapter.

Tokens
7K
Snippets
20
Records
20
Agent score
55%

What's inside Microsoft Graph SDK for Go

  1. How to authenticate with the Microsoft Graph SDK for Go

    main

    Authentication is handled by providing an AuthenticationProvider to a GraphRequestAdapter.

    A common method is using the DeviceCodeCredential from the azidentity package, which implements the device code flow.

    Important: To use device code flow, you must enable Allow public client flows in your app registration under the Authentication section in the Azure portal.

    import (
        azidentity "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
        "context"
        "fmt"
    )
    
    // Example using DeviceCodeCredential
    cred, err := azidentity.NewDeviceCodeCredential(&azidentity.DeviceCodeCredentialOptions{
        TenantID: "<the tenant id from your app registration>",
        ClientID: "<the client id from your app registration>",
        UserPrompt: func(ctx context.Context, message azidentity.DeviceCodeMessage) error {
            fmt.Println(message.Message)
            return nil
        },
    })
  2. Install the Microsoft Graph SDK for Go

    main

    To use the Microsoft Graph SDK in your Go project, install the main SDK and the Kiota Azure authentication module using go get:

    go get github.com/microsoftgraph/msgraph-sdk-go
    go get github.com/microsoft/kiota-authentication-azure-go
  3. Iterate through paginated results using PageIterator

    main

    When requesting collections (like Users), the results may be split across multiple pages. To retrieve all items, use the PageIterator from the msgraphcore package. This avoids manual handling of next links.

    To use it, you need:

    1. The initial collection response.
    2. The client's adapter (client.GetAdapter()).
    3. A discriminator function to create the collection response from the value (e.g., models.CreateUserCollectionResponseFromDiscriminatorValue).
    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"
    )
    
    // 1. Get the initial result
    result, err := client.Users().Get(context.Background(), nil)
    if err != nil {
        fmt.Printf("Error getting users: %v\n", err)
        return err
    }
    
    // 2. Initialize the PageIterator
    pageIterator, err := msgraphcore.NewPageIterator[models.Userable](result, client.GetAdapter(), models.CreateUserCollectionResponseFromDiscriminatorValue)
    
    // 3. Iterate through all pages
    err = pageIterator.Iterate(context.Background(), func(user models.Userable) bool {
        fmt.Printf("%s\n", *user.GetDisplayName())
        // Return true to continue to the next item/page
        return true
    })
  4. Make a request to get the user's drive

    main

    Once authenticated, you can navigate the Graph API using the client's fluent API. To retrieve the current user's drive, use client.Me().Drive().Get().

    import (
        "context"
        "fmt"
        "github.com/microsoftgraph/msgraph-sdk-go/models/odataerrors"
    )
    
    // Retrieve the user's drive
    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())
    
    // Helper to handle OData errors
    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)
        }
    }
  5. Initialize the Graph Service Client

    main

    Use msgraphsdk.NewGraphServiceClientWithCredentials to create a client instance. You must provide your credentials and a list of required scopes (e.g., []string{"Files.Read"}).

    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
    }
  6. Instantiate a GraphBaseServiceClient

    main

    To interact with the Microsoft Graph API, you must instantiate a GraphBaseServiceClient. This client serves as the main entry point for the SDK, providing access to the fluent API and managing configuration.

    When creating a client using NewGraphBaseServiceClient, you must provide:

    1. A RequestAdapter to handle the underlying HTTP requests.
    2. A BackingStoreFactory to manage the serialization and deserialization of data.

    By default, the client sets the base URL to https://graph.microsoft.com/v1.0 if no other URL is provided via the adapter.

    // Example instantiation (requires valid adapter and backing store)
    client := msgraphsdkgo.NewGraphBaseServiceClient(requestAdapter, backingStore)
  7. Access Microsoft Graph resources via GraphBaseServiceClient

    main

    The GraphBaseServiceClient acts as the primary entry point for interacting with various Microsoft Graph resources. It provides a set of methods, each returning a specific RequestBuilder (e.g., UsersRequestBuilder, SitesRequestBuilder, TeamsRequestBuilder). These request builders are used to construct and execute API requests against the corresponding Graph endpoints.

    Commonly used resource accessors include:

    • Users(): Manage user entities.
    • Sites(): Manage site entities.
    • Teams(): Manage team entities.
    • Security(): Manage the security singleton.
    • Search(): Manage the searchEntity singleton.
    • Organization(): Manage organization entities.
    • ServicePrincipals(): Manage service principal entities.

    Some methods allow for specific filtering or targeting via parameters, such as UsersWithUserPrincipalName(userPrincipalName *string) or ServicePrincipalsWithAppId(appId *string).

    // Example of accessing users and sites via the base service client
    // (Assuming 'client' is an initialized *GraphBaseServiceClient)
    
    // Access the users collection
    usersRequestBuilder := client.Users()
    
    // Access the sites collection
    sitesRequestBuilder := client.Sites()
    
    // Access a specific user collection by User Principal Name
    userByUPN := client.UsersWithUserPrincipalName("user@example.com")
  8. Initialize a GraphServiceClient with credentials and scopes

    main

    Use NewGraphServiceClientWithCredentials to instantiate a client using an Azure TokenCredential and a list of required OAuth2 scopes. This is the standard way to initialize the SDK for most applications.

    Parameters:

    • credential: An azcore.TokenCredential (e.g., from azidentity).
    • scopes: A slice of strings representing the permissions required.

    Returns the *GraphServiceClient or an error.

    import (
    	"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
    	"github.com/microsoftgraph/msgraph-sdk-go"
    )
    
    // Example using Azure Identity
    cred, err := azidentity.NewDefaultAzureCredential(nil)
    if err != nil {
    	// handle error
    }
    
    scopes := []string{"https://graph.microsoft.com/.default"}
    client, err := msgraphsdkgo.NewGraphServiceClientWithCredentials(cred, scopes)
    if err != nil {
    	// handle error
    }
  9. Initialize a GraphServiceClient with an existing RequestAdapter

    main

    Use NewGraphServiceClient to create a new client instance if you have already configured a RequestAdapter (from the Kiota abstractions). This is useful when you want to provide your own custom adapter implementation.

    client := msgraphsdkgo.NewGraphServiceClient(yourCustomAdapter)
  10. Initialize a GraphRequestAdapter

    main

    The GraphRequestAdapter is the core service used by the GraphBaseServiceClient to execute requests against the Microsoft Graph API. You can initialize it using several constructor functions depending on the level of customization required for parsing, serialization, or the underlying HTTP client.

    For most standard use cases, use NewGraphRequestAdapter by providing an AuthenticationProvider.

    // Standard initialization
    adapter, err := msgraphsdkgo.NewGraphRequestAdapter(authProvider)
    if err != nil {
        // handle error
    }