msgraphsdkgo

package module
v0.0.0-...-ad17228 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 7, 2023 License: MIT Imports: 80 Imported by: 0

README

Microsoft Graph SDK for Go

PkgGoDev

Get started with the Microsoft Graph SDK for Go by integrating the Microsoft Graph API into your Go application!

Note: this SDK allows you to build applications using the v1.0 of Microsoft Graph. If you want to try the latest Microsoft Graph APIs under beta, use our beta SDK instead.

Note: The Microsoft Graph Go SDK is currently in General Availability version starting from version 1.0.0. The SDK is considered stable, regular releases and updates to the SDK will however continue weekly..

1. Installation

go get github.com/microsoftgraph/msgraph-sdk-go
go get github.com/microsoft/kiota-authentication-azure-go

2. Getting started

2.1 Register your application

Register your application by following the steps at Register your app with the Microsoft Identity Platform.

2.2 Create an AuthenticationProvider object

An instance of the GraphRequestAdapter class handles building client. To create a new instance of this class, you need to provide an instance of AuthenticationProvider, which can authenticate requests to Microsoft Graph.

For an example of how to get an authentication provider, see choose a Microsoft Graph authentication provider.

Note: we are working to add the getting started information for Go to our public documentation, in the meantime the following sample should help you getting started.

This example uses the DeviceCodeCredential class, which uses the device code flow to authenticate the user and acquire an access token. This authentication method is not enabled on app registrations by default. In order to use this example, you must enable public client flows on the app registation in the Azure portal by selecting Authentication under Manage, and setting the Allow public client flows toggle to Yes.

import (
    azidentity "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
    "context"
)

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
    },
})

if err != nil {
    fmt.Printf("Error creating credentials: %v\n", err)
}

2.3 Get a Graph Service Client and Adapter object

You must get a GraphRequestAdapter object to make requests against the service.

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
}

3. Make requests against the service

After you have a GraphServiceClient that is authenticated, you can begin making calls against the service. The requests against the service look like our REST API.

3.1 Get the user's drive

To retrieve the user's drive:

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.GetError(); terr != nil {
			fmt.Printf("code: %s", *terr.GetCode())
			fmt.Printf("msg: %s", *terr.GetMessage())
		}
	default:
		fmt.Printf("%T > error: %#v", err, err)
	}
}

4. Getting results that span across multiple pages

Items in a collection response can span across multiple pages. To get the complete set of items in the collection, your application must make additional calls to get the subsequent pages until no more next link is provided in the response.

4.1 Get all the users in an environment

To retrieve the users:

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 error)
    return err
}

// Use PageIterator to iterate through all users
pageIterator, err := msgraphcore.NewPageIterator(result, client.GetAdapter(), models.CreateUserCollectionResponseFromDiscriminatorValue)

err = pageIterator.Iterate(context.Background(), func(pageItem interface{}) bool {
    user := pageItem.(models.Userable)
    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:", typed.Error())
                if terr := typed.GetError(); terr != nil {
                        fmt.Printf("code: %s", *terr.GetCode())
                        fmt.Printf("msg: %s", *terr.GetMessage())
                }
        default:
                fmt.Printf("%T > error: %#v", err, err)
        }
}

5. Documentation

For more detailed documentation, see:

6. Issues

For known issues, see issues.

7. Contributions

The Microsoft Graph SDK is open for contribution. To contribute to this project, see Contributing.

8. License

Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT license.

9. Third-party notices

Third-party notices

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetDefaultClientOptions

func GetDefaultClientOptions() core.GraphClientOptions

GetDefaultClientOptions returns the default client options used by the GraphRequestAdapterBase and the middleware.

Types

type GraphBaseServiceClient

GraphBaseServiceClient the main entry point of the SDK, exposes the configuration and the fluent API.

func NewGraphBaseServiceClient

NewGraphBaseServiceClient instantiates a new GraphBaseServiceClient and sets the default values.

func (*GraphBaseServiceClient) Admin

Admin provides operations to manage the admin singleton.

func (*GraphBaseServiceClient) AgreementAcceptances

AgreementAcceptances provides operations to manage the collection of agreementAcceptance entities.

func (*GraphBaseServiceClient) Agreements

Agreements provides operations to manage the collection of agreement entities.

func (*GraphBaseServiceClient) AppCatalogs

AppCatalogs provides operations to manage the appCatalogs singleton.

func (*GraphBaseServiceClient) ApplicationTemplates

ApplicationTemplates provides operations to manage the collection of applicationTemplate entities.

func (*GraphBaseServiceClient) Applications

Applications provides operations to manage the collection of application entities.

func (*GraphBaseServiceClient) AuditLogs

AuditLogs provides operations to manage the auditLogRoot singleton.

func (*GraphBaseServiceClient) AuthenticationMethodConfigurations

AuthenticationMethodConfigurations provides operations to manage the collection of authenticationMethodConfiguration entities.

func (*GraphBaseServiceClient) AuthenticationMethodsPolicy

AuthenticationMethodsPolicy provides operations to manage the authenticationMethodsPolicy singleton.

func (*GraphBaseServiceClient) CertificateBasedAuthConfiguration

CertificateBasedAuthConfiguration provides operations to manage the collection of certificateBasedAuthConfiguration entities.

func (*GraphBaseServiceClient) Chats

Chats provides operations to manage the collection of chat entities.

func (*GraphBaseServiceClient) Communications

Communications provides operations to manage the cloudCommunications singleton.

func (*GraphBaseServiceClient) Compliance

Compliance provides operations to manage the compliance singleton.

func (*GraphBaseServiceClient) Connections

Connections provides operations to manage the collection of externalConnection entities.

func (*GraphBaseServiceClient) Contacts

Contacts provides operations to manage the collection of orgContact entities.

func (*GraphBaseServiceClient) Contracts

Contracts provides operations to manage the collection of contract entities.

func (*GraphBaseServiceClient) DataPolicyOperations

DataPolicyOperations provides operations to manage the collection of dataPolicyOperation entities.

func (*GraphBaseServiceClient) DeviceAppManagement

DeviceAppManagement provides operations to manage the deviceAppManagement singleton.

func (*GraphBaseServiceClient) DeviceManagement

DeviceManagement provides operations to manage the deviceManagement singleton.

func (*GraphBaseServiceClient) Devices

Devices provides operations to manage the collection of device entities.

func (*GraphBaseServiceClient) Directory

Directory provides operations to manage the directory singleton.

func (*GraphBaseServiceClient) DirectoryObjects

DirectoryObjects provides operations to manage the collection of directoryObject entities.

func (*GraphBaseServiceClient) DirectoryRoleTemplates

DirectoryRoleTemplates provides operations to manage the collection of directoryRoleTemplate entities.

func (*GraphBaseServiceClient) DirectoryRoles

DirectoryRoles provides operations to manage the collection of directoryRole entities.

func (*GraphBaseServiceClient) DomainDnsRecords

DomainDnsRecords provides operations to manage the collection of domainDnsRecord entities.

func (*GraphBaseServiceClient) Domains

Domains provides operations to manage the collection of domain entities.

func (*GraphBaseServiceClient) Drives

Drives provides operations to manage the collection of drive entities.

func (*GraphBaseServiceClient) Education

Education provides operations to manage the educationRoot singleton.

func (*GraphBaseServiceClient) EmployeeExperience

EmployeeExperience provides operations to manage the employeeExperience singleton.

func (*GraphBaseServiceClient) External

External provides operations to manage the external singleton.

func (*GraphBaseServiceClient) FilterOperators

FilterOperators provides operations to manage the collection of filterOperatorSchema entities.

func (*GraphBaseServiceClient) Functions

Functions provides operations to manage the collection of attributeMappingFunctionSchema entities.

func (*GraphBaseServiceClient) GetAdapter

GetAdapter returns the client current adapter, Method should only be called when the user is certain an adapter has been provided

func (*GraphBaseServiceClient) GroupLifecyclePolicies

GroupLifecyclePolicies provides operations to manage the collection of groupLifecyclePolicy entities.

func (*GraphBaseServiceClient) GroupSettingTemplates

GroupSettingTemplates provides operations to manage the collection of groupSettingTemplate entities.

func (*GraphBaseServiceClient) GroupSettings

GroupSettings provides operations to manage the collection of groupSetting entities.

func (*GraphBaseServiceClient) Groups

Groups provides operations to manage the collection of group entities.

func (*GraphBaseServiceClient) Identity

Identity provides operations to manage the identityContainer singleton.

func (*GraphBaseServiceClient) IdentityGovernance

IdentityGovernance provides operations to manage the identityGovernance singleton.

func (*GraphBaseServiceClient) IdentityProtection

IdentityProtection provides operations to manage the identityProtectionRoot singleton.

func (*GraphBaseServiceClient) IdentityProviders

IdentityProviders provides operations to manage the collection of identityProvider entities.

func (*GraphBaseServiceClient) InformationProtection

InformationProtection provides operations to manage the informationProtection singleton.

func (*GraphBaseServiceClient) Invitations

Invitations provides operations to manage the collection of invitation entities.

func (*GraphBaseServiceClient) Localizations

Localizations provides operations to manage the collection of organizationalBrandingLocalization entities.

func (*GraphBaseServiceClient) Me

Me provides operations to manage the user singleton.

func (*GraphBaseServiceClient) Oauth2PermissionGrants

Oauth2PermissionGrants provides operations to manage the collection of oAuth2PermissionGrant entities.

func (*GraphBaseServiceClient) Organization

Organization provides operations to manage the collection of organization entities.

func (*GraphBaseServiceClient) PermissionGrants

PermissionGrants provides operations to manage the collection of resourceSpecificPermissionGrant entities.

func (*GraphBaseServiceClient) Places

Places the places property

func (*GraphBaseServiceClient) Planner

Planner provides operations to manage the planner singleton.

func (*GraphBaseServiceClient) Policies

Policies provides operations to manage the policyRoot singleton.

func (*GraphBaseServiceClient) Print

Print provides operations to manage the print singleton.

func (*GraphBaseServiceClient) Privacy

Privacy provides operations to manage the privacy singleton.

func (*GraphBaseServiceClient) Reports

Reports provides operations to manage the reportRoot singleton.

func (*GraphBaseServiceClient) RoleManagement

RoleManagement provides operations to manage the roleManagement singleton.

func (*GraphBaseServiceClient) SchemaExtensions

SchemaExtensions provides operations to manage the collection of schemaExtension entities.

func (*GraphBaseServiceClient) ScopedRoleMemberships

ScopedRoleMemberships provides operations to manage the collection of scopedRoleMembership entities.

func (*GraphBaseServiceClient) Search

Search provides operations to manage the searchEntity singleton.

func (*GraphBaseServiceClient) Security

Security provides operations to manage the security singleton.

func (*GraphBaseServiceClient) ServicePrincipals

ServicePrincipals provides operations to manage the collection of servicePrincipal entities.

func (*GraphBaseServiceClient) Shares

Shares provides operations to manage the collection of sharedDriveItem entities.

func (*GraphBaseServiceClient) Sites

Sites provides operations to manage the collection of site entities.

func (*GraphBaseServiceClient) Solutions

Solutions provides operations to manage the solutionsRoot singleton.

func (*GraphBaseServiceClient) SubscribedSkus

SubscribedSkus provides operations to manage the collection of subscribedSku entities.

func (*GraphBaseServiceClient) Subscriptions

Subscriptions provides operations to manage the collection of subscription entities.

func (*GraphBaseServiceClient) Teams

Teams provides operations to manage the collection of team entities.

func (*GraphBaseServiceClient) TeamsTemplates

TeamsTemplates provides operations to manage the collection of teamsTemplate entities.

func (*GraphBaseServiceClient) Teamwork

Teamwork provides operations to manage the teamwork singleton.

func (*GraphBaseServiceClient) TenantRelationships

TenantRelationships provides operations to manage the tenantRelationship singleton.

func (*GraphBaseServiceClient) Users

Users provides operations to manage the collection of user entities.

type GraphRequestAdapter

type GraphRequestAdapter struct {
	core.GraphRequestAdapterBase
}

GraphRequestAdapter is the core service used by GraphBaseServiceClient to make requests to Microsoft Graph.

func NewGraphRequestAdapter

func NewGraphRequestAdapter(authenticationProvider absauth.AuthenticationProvider) (*GraphRequestAdapter, error)

NewGraphRequestAdapter creates a new GraphRequestAdapter with the given parameters Parameters: authenticationProvider: the provider used to authenticate requests Returns: a new GraphRequestAdapter

func NewGraphRequestAdapterWithParseNodeFactory

func NewGraphRequestAdapterWithParseNodeFactory(authenticationProvider absauth.AuthenticationProvider, parseNodeFactory absser.ParseNodeFactory) (*GraphRequestAdapter, error)

NewGraphRequestAdapterWithParseNodeFactory creates a new GraphRequestAdapter with the given parameters Parameters: authenticationProvider: the provider used to authenticate requests parseNodeFactory: the factory used to create parse nodes Returns: a new GraphRequestAdapter

func NewGraphRequestAdapterWithParseNodeFactoryAndSerializationWriterFactory

func NewGraphRequestAdapterWithParseNodeFactoryAndSerializationWriterFactory(authenticationProvider absauth.AuthenticationProvider, parseNodeFactory absser.ParseNodeFactory, serializationWriterFactory absser.SerializationWriterFactory) (*GraphRequestAdapter, error)

NewGraphRequestAdapterWithParseNodeFactoryAndSerializationWriterFactory creates a new GraphRequestAdapter with the given parameters Parameters: authenticationProvider: the provider used to authenticate requests parseNodeFactory: the factory used to create parse nodes serializationWriterFactory: the factory used to create serialization writers Returns: a new GraphRequestAdapter

func NewGraphRequestAdapterWithParseNodeFactoryAndSerializationWriterFactoryAndHttpClient

func NewGraphRequestAdapterWithParseNodeFactoryAndSerializationWriterFactoryAndHttpClient(authenticationProvider absauth.AuthenticationProvider, parseNodeFactory absser.ParseNodeFactory, serializationWriterFactory absser.SerializationWriterFactory, httpClient *nethttp.Client) (*GraphRequestAdapter, error)

NewGraphRequestAdapterWithParseNodeFactoryAndSerializationWriterFactoryAndHttpClient creates a new GraphRequestAdapter with the given parameters Parameters: authenticationProvider: the provider used to authenticate requests parseNodeFactory: the factory used to create parse nodes serializationWriterFactory: the factory used to create serialization writers httpClient: the client used to send requests Returns: a new GraphRequestAdapter

type GraphServiceClient

type GraphServiceClient struct {
	GraphBaseServiceClient
}

func NewGraphServiceClient

func NewGraphServiceClient(adapter abstractions.RequestAdapter) *GraphServiceClient

func NewGraphServiceClientWithCredentials

func NewGraphServiceClientWithCredentials(credential azcore.TokenCredential, scopes []string) (*GraphServiceClient, error)

NewGraphServiceClientWithCredentials instantiates a new GraphServiceClient with provided credentials and scopes

func NewGraphServiceClientWithCredentialsAndHosts

func NewGraphServiceClientWithCredentialsAndHosts(credential azcore.TokenCredential, scopes []string, validhosts []string) (*GraphServiceClient, error)

NewGraphServiceClientWithCredentialsAndHosts instantiates a new GraphServiceClient with provided credentials , scopes and validhosts

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL